How to retrieve the hash value in an array in Ruby

When I touched Ruby for the first time in a long time, I didn't understand it so much that I was surprised, so I looked it up.

In the case of such an unpleasant array and hash combination.


user_data = [
  { user: { profile: { name: 'George', sex: 'man' } } },
  { user: { profile: { name: 'Alice', sex: 'woman' } } },
  { user: { profile: { name: 'Taro', sex: 'man' } } }

In the array, there is a hash called user, there is a hash called profile nested, and there is a value in the key named name ... I don't understand anymore.

Let's take this out.

Take out'George'.

Like this


puts user_data[0][:user][:profile][:name]

Of course, if you take out'Alice', it looks like this


puts user_data[1][:user][:profile][:name]

I just changed the position of the array.

If you want to retrieve the gender in the hash of'Alice'


puts user_data[1][:user][:profile][:sex]

I just changed: name to: sex.

Fetch all: names in the array

Since it is an array, use each to extract one by one.


user_data.each do |values|
  puts values[:user][:profile][:name]

The result will be



When using the dig method

From Ruby 2.3 onwards, dig is a new method that can be used in hash classes.

Try to retrieve'Gorge' with the dig method


puts user_data.dig(0, :user, :profile, :name)

If the hash is contained in an array, just enter the number of data you want in the argument.

Try to retrieve all': name' with the dig method


user_data.each do |values|
  puts values.dig(:user, :profile, :name)

Benefits of using the dig method

It seems to be the difference between returning with an error or nil when the key is not found. If you use dig, it will be returned as nil, so you do not need to take measures against errors. (Until then, he used to use the fetch method, etc.)


user_data = [
  {user: {}},
  {user: {}},
  {user: {}}

#When using dig
user_data.each do |values|
  puts values.dig(:user, :profile, :age)

#If you didn't use dig
user_data.each do |values|
  puts values[:user][:profile][:age]

The result looks like this


% ruby tmp/test.rb
#=> nil

#=> undefined method `[]' for nil:NilClass (NoMethodError)

Recommended Posts

How to retrieve the hash value in an array in Ruby
How to output the value when there is an array in the array
How to change a string in an array to a number in Ruby
[Ruby] How to retrieve the contents of a double hash
[Ruby] How to batch convert strings in an array to numbers
[Ruby] How to count even or odd numbers in an array
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
How to specify an array in the return value / argument of the method in the CORBA IDL file
How to build the simplest blockchain in Ruby
I want to get the value in Ruby
[Java] How to search for a value in an array (or list) with the contains method
[Rails] How to display an image in the view
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
If the parameter is an array, how to include it in Stopara's params.permit
How to iterate infinitely in Ruby
[Ruby] Extracting double hash in array
How to request by passing an array to the query with HTTP Client of Ruby
How to install Bootstrap in Ruby
[ruby] How to assign a value to a hash by referring to the value and key of another hash
How to add the same Indexes in a nested array
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
[Ruby] How to extract a specific value from an array under multiple conditions [select / each]
[Swift5] How to get an array and the complement of arrays
[Ruby] I want to put an array in a variable. I want to convert to an array
I want to change the value of Attribute in Selenium of Ruby
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
How to get date data in Ruby
How to add a new hash / array
How to pass the value to another screen
How to get the date in java
[Swift] How to pass the Label value in the selected collectionViewCell to the destination TextField
[Ruby] I want to extract only the value of the hash and only the key
How to convert an array of Strings to an array of objects with the Stream API
How to get the value after "_" in Windows batch like Java -version
How to get the setting value (property value) from the database in Spring Framework
How to change the value of a variable at a breakpoint in intelliJ
How to debug the processing in the Ruby on Rails model only on the console
[Swift] How to set an image in the background without using UIImageView.
Android development, how to check null in the value of JSON object
[Ruby] How to prevent errors when nil is included in the operation
How to create your own annotation in Java and get the value
How to find the cause of the Ruby error
How to check the logs in the Docker container
How to use an array for HashMap keys
How to add sound in the app (swift)
How to solve an Expression Problem in Java
[Ruby on Rails] How to install Bootstrap in Rails
How to build an executable jar in Maven
How to check Rails commands in the terminal
How to implement Pagination in GraphQL (for ruby)
[Ruby basics] How to use the slice method
Use hashes well in Ruby to calculate the total amount of an order
How to check if an instance variable is defined in a Ruby class
How to resolve errors that occur in the "Ruby on Rails" integration test
Initialize Ruby array with 0 like Java, that is, set the default value to 0
How to make a judgment method to search for an arbitrary character in an array
How to start a subscript from an arbitrary number in Ruby iterative processing
How to make an image partially transparent in Processing
How to install Ruby on an EC2 instance on AWS
[Ruby] How to use standard output in conditional branching