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.rb191 chars9 lines
Output:
main.rb34 chars2 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
.
gistlibby LogSnag