Get key value pair of hash for the given key , in ruby

Viewed 16145

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.

5 Answers

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

Related