I want to 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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With