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.

test.rb


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

test.rb


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

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

test.rb


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'

test.rb


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.

test.rb


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

The result will be

test.rb


George
Alice
Taro

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

test.rb


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

test.rb


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

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.)

test.rb


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

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

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

The result looks like this

test.rb


% 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 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
[Swift] How to get the number of elements in an array (super basic)
[Ruby] Count an even number in an array using the even? Method
Speed comparison when the value side of Hash wants to retrieve all with array
How to iterate infinitely in Ruby
How to request by passing an array to the query with HTTP Client of Ruby
How to install Bootstrap in Ruby
How to add the same Indexes in a nested array
[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
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 add a new hash / array
How to pass the value to another screen
How to get the date in java
[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 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
Android development, how to check null in the value of JSON object
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 solve an Expression Problem in Java
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
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
How to set the display time to Japan time in Rails
[Java] How to omit the private constructor in Lombok
How to use an array for a TreeMap key
[Ruby on Rails] How to write enum in Japanese
How to send value in HTML without screen transition
Examine the elements in the array using the [Ruby] includes? Method
[Ruby on Rails] How to change the column name
How to write to apply gem Pagy (pagination) to an array
[Java] How to get the maximum value of HashMap
Calculate the difference between numbers in a Ruby array
Organized how to interact with the JDK in stages
[Ruby On Rails] How to reset DB in Heroku