开发者

Check if hash has a key that contains some text

开发者 https://www.devze.com 2023-03-29 17:41 出处:网络
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:

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

精彩评论

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

关注公众号