1. Conclusion </ b>
2. How to code </ b>
3. What I learned from here </ b>
vegetables_price = [["tomato", [200, 250, 220]], ["potato", [100, 120, 80]], ["cabbage", [120, 150]]] #---❶
vegetables_price.each do |vegetable| #---❷
sum = 0
fruit[1].each do |price| #---❸
sum += price
end
puts "#{vegetable[0]}The total amount of#{sum}It's a yen" #---❹
end
❶: Vegetables_price is arranged in multiple arrays, and three types of amounts are arranged in tomato, potato, and cabbage. ❷: First, I want to extract each array in the first stage, so I use the each method to extract vegetables_price with vegetable. (ex: ["tomato", [200, 250, 220], ["potato", [100, 120, 80]], ["cabbage", [1200, 1500]]) ❸: In addition, the each method is used to extract the amount. I set sum = 0 in advance for output and calculate the total amount for each vegetable. [1] is because tomato is [0] and [200, 250, 220] is [1] because it is an array in the state of ["tomato", [200, 250, 220]. (ex: tomato➡︎200 + 250 + 220, potato➡︎100 + 120 + 80, cabbage➡︎120 + 150) ❹: Here, the name of each vegetable and the total amount of each are output. It is the same reason as ❸ to fix it with vegetable [0].
I thought it would be possible to make a double hash and sum only the amount of money entered with the desired name. So let's code using a key-value store.
Recommended Posts