[ACCEPTED]-Get key value pair of hash for the given key , in ruby-ruby

Accepted answer
Score: 16

There is a method, Hash#assoc can do similar 5 things. But it returns the key and value 4 in an array, which you can easily change 3 it into a hash. And an alternative is use 2 Hash#select, which does return a hash according 1 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"}
Score: 8

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"}

0

Score: 4

The most easy and native way are using the 3 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 2 multiples keys for this, for example, to 1 k1, and k3

k1 = :fish
k3 = :dog

h1.slice(k1, k3)
# => {:fish=>"aquatic animal", :dog=>"best human friend"}

Clear, easy and efficiently

Score: 2

Simplest answer:

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

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

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

Score: 0

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

More Related questions