I have a hash h1, and key k1. I need to return complete key value pair for the given key in the hash.
Like for key 'fish' i need to print 'fish' => 'aquatic animal'
@h1, prints all the key value pairs.I need the way to print the key value pair for thr given key
I am quite new to ruby, so sorry for the noobish question.
Ruby | Hash key() functionHash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil.
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 .
We can use the values method to return all the values of a hash in Ruby.
The most easy and native way are using the method slice
.
h1 = { fish: 'aquatic animal', tiger: 'big cat', dog: 'best human friend' }
k1 = :fish
Just do it:
h1.slice(k1)
# => {:fish=>"aquatic animal"}
And better, you can use multiples keys for this, for example, to k1, and k3
k1 = :fish
k3 = :dog
h1.slice(k1, k3)
# => {:fish=>"aquatic animal", :dog=>"best human friend"}
Clear, easy and efficiently
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