Am33d
Am33d

Reputation: 450

Get a value from an array of hashes in ruby

I have an array of hashes:

ary = [{1=>"January", 2=>"February", 3=>"March"}, {11=>"Oct", 12=>"Nov", 13=>"Dec"}]

How can I get the value from a particular hash, based on a key? I would like to do something like:

ary[1].select{|h| h[13]} 

to get the value "Dec" from the second hash with the key 13. The above statement returns the whole second hash, which is not the requirement:

{11=>"Oct", 12=>"Nov", 13=>"Dec"}

Upvotes: 3

Views: 13339

Answers (3)

Firstly make a single hash and then return the value of hash by key.

Make single hash from array with merging elements.

  • Method 1

    hash = ary.reduce({}, :merge)

  • Method 2

    hash = ary.inject(:merge)

Then return the value by key.

hash[13]

Upvotes: 0

ArMD
ArMD

Reputation: 404

The select statement will return all the hashes with the key 13.

If you already know which hash has the key then the below code will give u the answer.

ary[1][13]

However if you are not sure which of your hashes in the array has the value, then you could do the following:

values = ary.map{|h| h[13]}.compact

Values will have the value of key 13 from all the hashes which has the key 13.

Upvotes: 3

Kostas Sklias
Kostas Sklias

Reputation: 51

You can merge the two hashes in one and then query the keys of the merged hash.

c = a.merge(b)
  => {1=>"January", 2=>"February", 3=>"March", 11=>"Oct", 12=>"Nov", 13=>"Dec"}

And then you can do something like:

c[1]
  => "January"

Otherwise, if you want to keep the format as an array of different hashes you can just get the value you want this way:

ary[1][12]
  => "Nov"

But that way you have to always know in which hash inside the array is the element you want, which seems a bit confusing because you could just use different hashes instead of an array of hashes and having to remember each hash's position inside the array.

Upvotes: 0

Related Questions