[Ruby] each nested

Overview

Here is a summary of how to use the each method in a nested manner for learning.

environment

Ruby 2.6.5

Contents

As an example, for the following sequence

vegetables_price = [["tomato", [120, 150, 80]], ["potato", [50, 60, 40]], ["carrot", [120, 150]]]

Suppose you want the following output result.

The total amount of tomato is 350 yen
The total amount of potato is 150 yen
The total amount of carrot is 270 yen

Description

vegetables_price = [["tomato", [120, 150, 80]], ["potato", [50, 60, 40]], ["carrot", [120, 150]]]

vegetables_price.each do |vegetable| #Array vegetables_Use each method for price.
  sum = 0 #Define a variable sum to store the total value
  vegetable[1].each do |price| #Variable vegetable[1]Use each method for.[1]Has a price.
    sum += price #Turn each to add the price.
  end
  puts "#{vegetable[0]}The total amount of#{sum}It's a yen" #vegetable[0]Contains the name of vegetable.
end
vegetables_price = [["tomato", [120, 150, 80]], ["potato", [50, 60, 40]], ["carrot", [120, 150]]]
   (Subscript)                0              1

that's all

Recommended Posts

[Ruby] each nested
[Ruby] Nesting each
Nested structure of each
[Ruby] Various types of each
[Ruby] Review about nesting of each
Gem list of each ruby version 2.5.x
Ruby learning 4
[Ruby] Array
Ruby basics
Ruby Review 2
Ruby addition
Refactoring Ruby
[Ruby] Simplify each using map and inject
Ruby learning 3
Ruby setting 2
Ruby problem ⑦
Ruby learning 2
[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? ??