简体   繁体   English

使用Ruby查询具有多个值的哈希数组

[英]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 我想选择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? between?可以利用between?

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

This will return you only the hash which has age between 26 and 27 这只会返回age2627之间的哈希

Or You can use include? 或者您可以使用include? to check for specific age 检查特定年龄

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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