[About double hash]

●●● 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

[About double hash]
[ruby] Double hash
Ruby double hash
[Rails] About active hash
hash
Hash
gem active_hash About active hash
About =
About the behavior of ruby Hash # ==
Extraction of "ruby" double hash * Review
[Ruby] Extracting double hash in array
About method.invoke
About Kotlin
About attr_accessor
About Hinemos
About inheritance
About params
About Docker
About form_for
About Spring ③
About polymorphism
About Optional
About hashes
About JitPack
About Dockerfile
About this ()
About devise
About encapsulation
About Docker
About JAVA_HOME
About active_hash
About static
About exceptions
Hash basics
About scope
[Maven] About Maven