1

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.

2 Answers 2

4

This will do it:

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

10 Comments

Why would you use between? in this situation. There is nothing in OP's question that would suggest that it's appropriate.
@EricDuminil, when I see include?, I think one of, when I see between? I think within the bounds of. Both are equally easy to read, only one is what OP wanted. What if 26 and 27 were just an example?
@ndn: Both work fine with this example. I find between? even more readable than include? in this case : read as an english sentence, the first example is easier to parse IMHO.
@EricDuminil, a lot of things might work with the example's values. It doesn't mean they are correct in the general case.
@ndn: True, but only the OP knows what the general case is. Without more info, I find it harsh to say that this answer isn't appropriate.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.