If it is an "array", it can be easily retrieved, but if it is an "array inside an array",
――I think a little ――I can't get the value I want
It is an article for those who say. I hope you find it helpful.
--Practice --Problem --Answer (commentary) --Process
--Summary --References
Output the fruit name and total amount from the following array.
problem
fruits_price = [["apple", [200, 300, 400]], ["banana", [100, 200, 300]], ["grape", [2000, 3000]]]
Answer example
fruits_price.each do |fruit|
# fruits_Extract the array one by one from price and extract it with fruit(By using each, you can process the array in the array.)
sum = fruit[1].sum
# fruit[1](Amountpart)sum(Totalamount)
puts "#{fruit[0]}The total amount of#{sum}It's a yen"
#output
end
Another solution
fruits_price.each do |fruits, prices|
puts "#{fruits}The total amount of#{prices.sum}It's a yen"
end
** 1. Think about what you want to get **
--Fruit name --Total amount of each fruit
** 2. How to retrieve elements for arrays **
--Retrieve with each
――What number of them to get
** 3. How to get the total value **
--Output sum of elements with sum
--Think about what value you want to take
--Isolate the problem and find out how to output it.
--You can easily get the sum of elements with sum
-Ruby 3.0.0 Reference Manual (sum)
Recommended Posts