rmn.nish
rmn.nish

Reputation: 889

Query array of hashes with multiple values using Ruby

I have an array of hashes as follows:

array = [{"name"=>"Nish", "age"=>27, "place"=>"xyz"},
         {"name"=>"Hari", "age"=>26, "place"=>"xyz"},
         {"name"=>"Anan", "age"=>28, "place"=>"xyz"}]

I want to select the hashes with age 27 and 26

How to achieve that.

Upvotes: 1

Views: 676

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

You can make use of between?

array.select{ |a| a['age'].between?(26, 27) }

This will return you only the hash which has age between 26 and 27

Or You can use include? to check for specific age

array.select{ |a| [26, 27].include? a['age'] }

Upvotes: 2

RichardAE
RichardAE

Reputation: 2970

This will do it:

array.select { |user| [26, 27].include?(user['age']) }

The 'select' will choose any elements that match the provided block.

Upvotes: 4

Related Questions