Himz
Himz

Reputation: 523

Get key value pair of hash for the given key , in 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.

Upvotes: 14

Views: 17734

Answers (5)

Luiz Carvalho
Luiz Carvalho

Reputation: 1419

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

Upvotes: 4

aaron-coding
aaron-coding

Reputation: 2621

Simplest answer:

def find(k1)
  {k1 => h1[k1]}
end

this will return {'fish' => 'aquatic animal'} which is what you need.

no need to jump through hoops to get they key, since you already have it! :-)

Upvotes: 2

zloydadka
zloydadka

Reputation: 160

in ruby >= 1.9

value_hash = Hash[*h1.assoc(k1)]
p value_hash                 # {"fish"=>"aquatic animal"}

in ruby < 1.9

value_hash = Hash[k1, h1[k1]]
p value_hash                 # {"fish"=>"aquatic animal"}

Upvotes: 8

halfelf
halfelf

Reputation: 10107

There is a method, Hash#assoc can do similar things. But it returns the key and value in an array, which you can easily change it into a hash. And an alternative is use Hash#select, which does return a hash according to the block given.

h1 = { "fish" => "aquatic animal", "tiger" => "big cat" }
h1.assoc "fish"                       # ["fish", "aquatic animal"]
h1.select { |k,v| k == "fish" }       # {"fish"=>"aquatic animal"}

Upvotes: 16

Himz
Himz

Reputation: 523

I got a workaround, by creating a new hash, from the key value pair, and then outputting its value by using puts h1

Upvotes: 0

Related Questions