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.
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.
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
From Ruby 2.3 onwards, dig is a new method that can be used in hash classes.
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.
test.rb
user_data.each do |values|
puts values.dig(:user, :profile, :name)
end
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