Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string includes any of the keys in a hash and return the value of the key it contains

Tags:

string

ruby

hash

I have a hash with multiple keys and a string which contains either none or one of the keys in the hash.

h = {"k1"=>"v1", "k2"=>"v2", "k3"=>"v3"}
s = "this is an example string that might occur with a key somewhere in the string k1(with special characters like (^&*$#@!^&&*))"

What would be the best way to check if s contains any of the keys in h and if it does, return the value of the key that it contains?

For instance, for the above examples of h and s, the output should be v1.

Edit: Only the string would be user defined. The hash will always be the same.

like image 335
Sid Avatar asked Apr 21 '15 04:04

Sid


2 Answers

I find this way readable:

hash_key_in_s = s[Regexp.union(h.keys)]
p h[hash_key_in_s] #=> "v1"

Or in one line:

p h.fetch s[Regexp.union(h.keys)] #=> "v1"

And here is a version not using regexp:

p h.fetch( h.keys.find{|key|s[key]} ) #=> "v1"
like image 123
hirolau Avatar answered Oct 13 '22 23:10

hirolau


create a regex out of Hash h keys and match in string:

h[s.match(/#{h.keys.join('|')}/).to_s]
# => "v1"

Or as Amadan suggested using Regexp#escape for safety:

h[s.match(/#{h.keys.map(&Regexp.method(:escape)).join('|')}/).to_s]
# => "v1"

If String s was evenly spaced, we could have done something like this too:

s =  "this is an example string that might occur with a key somewhere in the string k1 (with special characters like (^&*$\#@!^&&*))"
h[(s.split & h.keys).first]
# => "v1"
like image 36
shivam Avatar answered Oct 14 '22 00:10

shivam