get specific key value from array of hashes in ruby
To get a specific key value from an array of hashes in Ruby, you can follow these steps:
- Define the array of hashes.
- Use the
map
method to create a new array containing the values of the specific key. - Access the specific key value using the index of the array.
Here's an example of the code:
# Step 1: Define the array of hashes
array_of_hashes = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
]
# Step 2: Use the `map` method to create a new array containing the values of the specific key
specific_key_values = array_of_hashes.map { |hash| hash[:name] }
# Step 3: Access the specific key value using the index of the array
puts specific_key_values[1] # Output: "Bob"
In this example, we have an array of hashes with keys "name" and "age". We use the map
method to create a new array containing the values of the "name" key. Finally, we access the specific key value using the index of the array.