Inside the array is user_data, which has the information of multiple users as a hash.
user_data = [ {user: {profile: {name: 'Ken' }}},
{user: {profile: {name: 'Ichiro' }}},
{user: {profile: {name: 'Yuki'
}}},
]
#Output result in terminal
Ken
Ichiro
Yuki
What if you want to use user_data and code in Ruby so that only the names of all users are output?
To get a specific value from a hash
hash[The key of the value you want to get]
You can get it at. If you want to get a specific value from a double hash, you can get it by continuously specifying the key of the value you want to get.
hash[The key of the value you want to get][The key of the value you want to get]
In this case, I want to get the name, so
hash[:user][:profile][:name]
You can get it at.
Also, since the hashes are stored in the array, it is necessary to extract each hash and extract the name in each statement.
Therefore
user_data = [ {user: {profile: {name: 'Ken' }}},
{user: {profile: {name: 'Ichiro' }}},
{user: {profile: {name: 'Yuki'
}}},
]
#The name in
user_data.each do |u|
puts u[:user][:profile][:name]
end
You can retrieve the name by writing as follows.
Recommended Posts