select from an array whose elements are hashes in ruby

To select elements from an array whose elements are hashes in Ruby, you can use the select method with a block.

Here's an example:

main.rb
array = [
  { name: 'John', age: 30 },
  { name: 'Sarah', age: 25 },
  { name: 'Mike', age: 40 }
]

selected_elements = array.select { |hash| hash[:age] > 30 }
puts selected_elements.inspect
191 chars
9 lines

Output:

main.rb
[{ :name => 'Mike', :age => 40 }]
34 chars
2 lines

In this example, we have an array of hashes representing people's information. We use the select method to select the elements from the array that match a specific condition. In this case, we select the hashes where the :age key has a value greater than 30.

The select method iterates over each element of the array and passes it to the block. The block should return a truthy value if the element should be selected. In this case, we access the :age value of each hash using the [:age] syntax and compare it with the desired condition.

The result is a new array containing only the hashes that satisfy the condition.

Note: If you want to modify the original array and remove the elements that do not match the condition, you can use the select! method instead of select.

related categories

gistlibby LogSnag