●●● Problem ●●● Suppose you have the following array user_data.
user_data = [
{
user: {
profile: {
name: 'George'
}
}
},
{
user: {
profile: {
name: 'Alice'
}
}
},
{
user: {
profile: {
name: 'Taro'
}
}
}
]
From here, extract only the user name so that the output looks like the one below.
George
Alice
Taro
●●● Answer ●●●
user_data.each do |u|
puts u[:user][:profile][:name]
end
Or
user_data.each{ |u| puts u.dig(:user, :profile, :name) }
●●● Explanation ●●●
First of all, how to retrieve the hash.
hash[The key of the value you want to get]
#Example
user = {name:Taro}
user[:name]
#=> "Taro"
Checking the structure of the array user_data in question
First element of the array
{user:{profile:{name:'George'}}}
Second element of the array
{user:{profile:{name:'Alice'}}}
Third element of the array
{user:{profile:{name:'Taro'}}}
You can see that it is. The each method is used for the array user_data, and the name key is extracted for each element of the array. Therefore, the answer is as above.
Recommended Posts