简体   繁体   中英

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.

This will do it:

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

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

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'] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM