[Ruby] Ruby 2D array

less than 1 minute read

What is a two-dimensional array?

A two-dimensional array is an array in which the array is contained in the array used in the program.

Source code

fruits_price = [["apple", [200, 250, 220]], ["orange", [100, 120, 80]], ["melon", [1200, 1500]]] # array key total price calculation

fruits_price.each do |fruit|
  sum = 0
  fruit[1].each do |price|
    sum += price
  end
  puts "The total amount of #{fruit[0]} is #{sum} yen"
end

result

The total amount of apple is 670 yen
The total amount of orange is 300 yen
The total amount of melon is 2700 yen

Explanation

key is the name of the fruit, value is the price of the fruit in array

[["apple", [200, 250, 220]]

Ruby each statement

Object .each do | variable |
  Processing to perform 1
  Process 2 to perform
end

Here we are taking out the elements one by one.

fruits_price.each do |fruit|
  sum = 0
  fruit[1].each do |price|
    sum += price
  end

Now, take out the elements for the array that contains the price in the array, Store in sum.

This is completed.