When each statement is nested, it is difficult to read, so I tried to summarize what to think.
shopping_price = [["Vegetables", [200, 250, 220]], ["fruits", [1200, 1500]]]
If there is an array in the array in the first place, how to retrieve the value in it?
It can be taken out by overlapping the subscripts.
If you retrieve the 1200
in the above array,
puts shopping_price[1][1][0]
Will be.
The basic description is
Array.each do |Block parameters (variables)|
#Processing you want to repeat
end
Block parameters are variables that can only be handled in do ~ end
. As an image, it feels like the array goes in one by one.
If the name of the array is plural, it is often the singular.
shopping_price = [["Vegetables", [200, 250, 220]], ["fruits", [1200, 1500]]]
shopping_price.each do |shopping|
sum = 0
shopping[1].each do |price|
sum += price
end
puts "#{shopping[0]}The total amount of#{sum}"
end
#=>The total amount of vegetables is 670 yen
#=>The total amount of fruit is 2700 yen
In the outside each statement,
The first time [" vegetables ", [200, 250, 220]]
The second time [" fruit ", [1200, 1500]]
But|shopping|
Go inside.
Shopping [1]
is applied to the array of each statement inside.
In other words
The first time [200, 250, 220]
The second time [1200, 1500]
Goes into price
.
The first calculation is sum = 0 + 200 sum = 200 + 250 sum = 450 + 220
Will be.
In shopping [0], vegetables
and fruits
are included respectively.
There are a lot of [square brackets] and it's hard to read, but any [square brackets] is required. Refactoring may be necessary because the foreach statement in each statement and the array in the array are difficult to read.