开发者

Check if hash has a key that contains some text

I want t开发者_运维问答o check if a hash has a key that contains some text. It may not be the exact key, but the key must contains (like the .include?) the text. My solution for this is:

some_hash.select {|k,v| k.include? "foo"}.empty?

But this will generate one more hash. I just want to check the existence of the key. Is there a better way to do that?


This would be a little nicer:

some_hash.any? {|k, v| k.include? "foo"}

(To me this reads as "does the hash have any keys which include 'foo'?")

Alternatively, this may be less efficient, but actually be a little more efficient (see comments), and perhaps a little more readable:

some_hash.keys.any? {|k| k.include? "foo"}


some_hash.keys.any? {|k| k.include? 'foo' }


some_hash.any? {|k,v| k.include? "foo"}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜