[Ruby] Nesting each

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.

problem

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

answer

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

Commentary

① 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.

bonus

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

[Ruby] Nesting each
[Ruby] each nested
[Ruby] Review about nesting of each
[Ruby] Various types of each
Gem list of each ruby version 2.5.x
Ruby learning 4
[Ruby] Array
Ruby basics
Ruby learning 5
Ruby basics
Refactoring Ruby
[Ruby] Simplify each using map and inject
Ruby learning 3
Ruby setting 2
Ruby learning 2
Nesting routing ...
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
Ruby settings 1
Refactoring Ruby
Ruby basics
Ruby memo
Ruby learning 1
Ruby Review 1
[Ruby] Module
[Ruby] What if you put each statement in each statement? ??