[Ruby] [Ruby]each nesting

less than 1 minute read

Overview

I will summarize how to use each method in nesting for learning. *We do not touch on what each method is.

environment

Ruby 2.6.5

Content

As an example, for an array like

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 content

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

vegetables_price.each do |vegetable| # Use each method for array vegetables_price.
  sum = 0 # Defines a variable sum that stores the total value
  vegetable[1].each do |price| # use each method for variable vegetable[1]. [1] contains the price.
    sum += price Turn #each to add the price.
  end
  puts "The total amount of #{vegetable[0]} is #{sum} yen"  #vegetable[0] contains the name of vegetable.
end
  • Remarks The subscript 0 means the vegetable name and 1 means the price.
vegetables_price = [["tomato", [120, 150, 80]], ["potato", [50, 60, 40]], ["carrot", [120, 150]]]
   (Subscript) 0 1

that’s all

Tags:

Updated: