加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby hash:返回第一个不是nil的键值

发布时间:2020-12-17 01:25:01 所属栏目:百科 来源:网络整理
导读:说我有哈希 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 可
说我有哈希

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,calls ifnone and returns its
result when it is specified,or returns nil otherwise.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读