Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 200
Himz Avatar asked Aug 21 '12 01:08

Himz


People also ask

How do you get the key of hash in Ruby?

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.

How do you check if a key-value exists in a hash Ruby?

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 .

How can you get all the values of a hash in an array Ruby?

We can use the values method to return all the values of a hash in Ruby.


1 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

like image 59
Luiz Carvalho Avatar answered Oct 03 '22 07:10

Luiz Carvalho