A two-dimensional array is an array that is used in a program and contains an array inside the array.
fruits_price = [["apple", [200, 250, 220]], ["orange", [100, 120, 80]], ["melon", [1200, 1500]]] #Array Key Total amount calculation
fruits_price.each do |fruit|
sum = 0
fruit[1].each do |price|
sum += price
end
puts "#{fruit[0]}The total amount of#{sum}It's a yen"
end
The total amount of apple is 670 yen
The total price of orange is 300 yen
The total amount of melon is 2700 yen
[["apple", [200, 250, 220]]
object.each do |variable|
Process to be executed 1
Process to be executed 2
end
Here we are taking out the elements one by one.
fruits_price.each do |fruit|
sum = 0
fruit[1].each do |price|
sum += price
end
Now, take out the elements for the array that contains the price in the array, Store in the sum.
That's all there is to it.
Recommended Posts