We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.
Do you know a pretty ruby way to find if an hash has one of some keys ?
h = {:a => 1, :c => 3, :d => 4} # keys to find are :a, :b or :e
I know that I can do a :
h.key?(:a) || h.key?(:b) || h.key?(:e)
But I was wondering if there was a prettier way to do it ! :)
Thanks a lot !
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