ruby如果散列键包含文本,则返回散列键(ruby if hash keys include text, return hash key)
我有这样的哈希:
hash = {2013 => 'one', 2014 => 'two'}
和一个可变number :
number = 13
我需要搜索所有的哈希键,如果键中包含number ,我需要返回该键。 现在我有这个:
if hash.keys.any? {|k| k.include? number} #do some work end这是有效的,但实际上我需要在k确实包含number的情况下返回k ,而不仅仅是检查它。 如何以上面的块“if”格式轻松编写。
I have a hash like so:
hash = {2013 => 'one', 2014 => 'two'}
and a variable number:
number = 13
I need to search through all of my hash keys and if number is included in a key, I need to return that key. Right now I have this:
if hash.keys.any? {|k| k.include? number} #do some work endThat works, but I actually need to return k in the case that k does include number, not just check for it. How can I write that easily in a block "if" format like above.
最满意答案
使用find :
if result = hash.keys.find {|k| k.include? number} #do some work endUse find:
if result = hash.keys.find {|k| k.include? number} #do some work end更多推荐
发布评论