This article uses Ruby 2.6.5 installed on macOS Catalina 10.15.6.
--_ This is a form in which an array is contained in an array __. --Each item is stored as an array in the hash of items_price. ――In addition, there is an array of names and prices in each item.
items_price = [["pen", [100, 200, 120]], ["book", [120, 150, 220]], ["pen_case", [1000, 1500]]]
--Use each statement to retrieve the hash. ――This time it's two-dimensional, so you use each statement twice.
items_price = [["pen", [100, 200, 120]], ["book", [120, 150, 220]], ["pen_case", [1000, 1500]]]
items_price.each do |item|
sum = 0
item[1].each do |price|
sum += price
end
puts "#{item[0]}The price of#{sum}It is a circle."
end
Let's take pen as an example and look at it one by one.
items_price.each do |item| ~ end
# => items_In the price array["pen", [100, 200, 120]]Is taken out and assigned to the block variable item
item[1].each do |price| ~ end
# =>In the item array[100, 200, 120]And assign it to the block variable price
--By the way, item [1] is the number of elements in the price array, that is, it will be repeated 3 times here.
puts "#{item[0]}The price of#{sum}It is a circle."
--item [0] is the "pen" part of the item array with 0 subscripts and ["pen", [100, 200, 120]].
The price of the pen is 420 yen.
The price of the book is 490 yen.
pen_The price of the case is 2500 yen.
Recommended Posts