哪个键值先出现非nil,请告诉我?
- 内容介绍
- 文章标签
- 相关推荐
本文共计382个文字,预计阅读时间需要2分钟。
在Ruby中,我们可以通过哈希和数组结合使用,实现类似Python中的字典推导式的功能。以下是一个示例代码,它检查给定的哈希中是否存在一个键对应的值不为nil:
rubyhash={a: 1, b: false, c: nil}keys=[c, b, a]
result=keys.select { |key| hash[key] !=nil }.first
puts result==nil
这段代码首先定义了一个哈希`hash`,然后定义了一个包含键的数组`keys`。使用`select`方法过滤出哈希中值不为nil的键,并使用`first`方法获取第一个满足条件的键。最后,输出该键是否为nil。
说我有哈希hash = {a:1, b:false, c:nil}
&安培;某处的一系列键:[:c,:b,:a].是否有一个Ruby习惯用于返回这样一个键值!= nil?
obv
[:c, :b, :a].select {|key| hash[key] != nil}.first # returns :b
似乎太长了.
为此,我认为Enumerable#find可能有效:
find(ifnone = nil) { |obj| block } → obj or nil find(ifnone = nil) → an_enumerator
Passes each entry in enum to block. Returns the first for which block
is not false. If no object matches, callsifnoneand returns its
result when it is specified, or returnsnilotherwise.If no block is given, an enumerator is returned instead.
在你的情况下,它将返回第一个块不是nil:
p %i[c b a].find { |key| !{ a: 1, b: nil, c: nil }[key].nil? } # :a p %i[c b a].find { |key| !{ a: 1, b: 1, c: nil }[key].nil? } # :b
本文共计382个文字,预计阅读时间需要2分钟。
在Ruby中,我们可以通过哈希和数组结合使用,实现类似Python中的字典推导式的功能。以下是一个示例代码,它检查给定的哈希中是否存在一个键对应的值不为nil:
rubyhash={a: 1, b: false, c: nil}keys=[c, b, a]
result=keys.select { |key| hash[key] !=nil }.first
puts result==nil
这段代码首先定义了一个哈希`hash`,然后定义了一个包含键的数组`keys`。使用`select`方法过滤出哈希中值不为nil的键,并使用`first`方法获取第一个满足条件的键。最后,输出该键是否为nil。
说我有哈希hash = {a:1, b:false, c:nil}
&安培;某处的一系列键:[:c,:b,:a].是否有一个Ruby习惯用于返回这样一个键值!= nil?
obv
[:c, :b, :a].select {|key| hash[key] != nil}.first # returns :b
似乎太长了.
为此,我认为Enumerable#find可能有效:
find(ifnone = nil) { |obj| block } → obj or nil find(ifnone = nil) → an_enumerator
Passes each entry in enum to block. Returns the first for which block
is not false. If no object matches, callsifnoneand returns its
result when it is specified, or returnsnilotherwise.If no block is given, an enumerator is returned instead.
在你的情况下,它将返回第一个块不是nil:
p %i[c b a].find { |key| !{ a: 1, b: nil, c: nil }[key].nil? } # :a p %i[c b a].find { |key| !{ a: 1, b: 1, c: nil }[key].nil? } # :b

