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.
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"
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"
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