Check if the string contains any of the keys in the hash and returns the value of the key containing it

I have a hash with several keys and a string that contains none, none 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 so, return the value of the key that it contains?

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

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

+5
source share
2 answers

I find this method readable:

 hash_key_in_s = s[Regexp.union(h.keys)] ph[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" 
+5
source

create a regex from Hash h and match in a line:

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

Or, since Amadan suggested using Regexp # escape for security:

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

If the string s was evenly distributed, we could do something like this:

 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" 
+3
source

All Articles