Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if hash has a key that contains some text

Tags:

string

ruby

hash

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?

like image 296
Fábio Perez Avatar asked Aug 18 '11 23:08

Fábio Perez


2 Answers

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"}
like image 91
jtbandes Avatar answered Sep 30 '22 16:09

jtbandes


some_hash.keys.any? {|k| k.include? 'foo' }
like image 32
Jörg W Mittag Avatar answered Sep 30 '22 14:09

Jörg W Mittag