I am reviewing the drill to strengthen my logical thinking. As a beginner, I would appreciate it if you could let me know if you have any questions.
Use the array below to write the name of the fruit and the code that will output the total amount of each.
fruits_price = [["banana", [160, 100, 220]], ["kiwi", [100, 250, 80]], ["strawberry", [700, 680]]]
#output
The total amount of banana is 480 yen.
The total amount of kiwi is 430 yen
The total amount of strawberry is 1380 yen
fruits_price = [["banana", [160, 100, 220]], ["kiwi", [100, 250, 80]], ["strawberry", [700, 680]]]
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
① Take out ["apple", [200, 250, 220]] from fruits_price Each does not decompose and extract all the elements in the array, but extracts them in the next small chunk in the array applied to each.
In this case
From [["banana", [160, 100, 220]], ["kiwi", [100, 250, 80]], ["strawberry", [700, 680]]]
1st → ["banana", [160, 100, 220]]
2nd → ["kiwi", [100, 250, 80]]
3rd time → ["strawberry", [700, 680]]
It is taken out in the order of.
② Extract [160, 100, 220] from ["banana", [160, 100, 220]] and calculate.
The value of the contents of a variable can be represented by a subscript. For example, if fruit = [banana, kiwi, strawberry], then: fruit[0] = banana fruit[1] = kiwi fruit[2] = strawberry
This time, because there is an array in the array, it is easy to think difficult, but the idea is the same. Currently ["banana", [160, 100, 220]] is stored in a variable called fruit, so it looks like this: fruit[0] = banana fruit[1] = [160, 100, 220]
Multiply fruit [1] by each to take out the numbers one by one and add the numbers while self-substituting.
③ Output with puts
As mentioned in ②, the fruit name can be retrieved with fruit [0].
And the variable that stores the total amount is output by expression expansion together with sum.
Below are my mistakes.
fruit[1].each do |price|
sum += price
puts "#{fruit[0]}The total amount of#{sum}It's a yen"
end
If you put puts in the block of fruit [1] .each like this The amount in the middle of calculation is also output every time, so it will be an error.
Recommended Posts