rails filter hashes by key value
# Example Hashes
hashes = [
{ name: 'Alice', age: 30, city: 'New York' },
{ name: 'Bob', age: 25, city: 'San Francisco' },
{ name: 'Charlie', age: 35, city: 'Los Angeles' }
]
# Step 1: Define the key-value pair to filter by
key_to_filter = :age
value_to_filter = 30
# Step 2: Use the select method to filter hashes based on the key-value pair
filtered_hashes = hashes.select { |hash| hash[key_to_filter] == value_to_filter }
# Step 3: Display the filtered hashes
puts "Filtered Hashes:"
puts filtered_hashes
This Ruby code defines an array of hashes, filters the hashes based on a specified key-value pair, and then displays the filtered hashes. Replace the values of key_to_filter
and value_to_filter
with the desired key and value for filtering.