说我有哈希 hash = {a:1, b:false, c:nil} 安培;某处的一系列键:[:c,:b,:a].是否有一个Ruby习惯用于返回这样一个键值!= nil? obv [:c, :b, :a].select {|key| hash[key] != nil}.first # returns :b 似乎太长了
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
