Ruby two-dimensional array

What is a two-dimensional array?

A two-dimensional array is an array that is used in a program and contains an array inside the array.

Source code

fruits_price = [["apple", [200, 250, 220]], ["orange", [100, 120, 80]], ["melon", [1200, 1500]]] #Array Key Total amount calculation

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

result

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

Description

The key is the name of the fruit, and the value is the price of the fruit.

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

Ruby each statement

object.each do |variable|
Process to be executed 1
Process to be executed 2
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 the sum.

That's all there is to it.

Recommended Posts

Ruby two-dimensional array
[Ruby] Array
[Ruby] Extracting a two-dimensional array
Ruby array manipulation
Multiplication in a Ruby array
Array
Learning Ruby with AtCoder 13 How to make a two-dimensional array
Hanachan in Ruby (non-destructive array manipulation)
Explanation about Array object of Ruby
What is a Ruby 2D array?
Ruby learning 4
[Java] array
Java array
Array practice
Ruby learning 5
Ruby basics
Ruby Review 2
Ruby addition
Java array
[Java] Array
Ruby learning 3
Ruby setting 2
Java array
Ruby problem ⑦
Ruby learning 2
Ruby learning 6
12 of Array
Ruby settings 1
java array
Sort an array of Ruby homebrew classes
[Java] Array
Ruby learning 1
Ruby Review 1
Two-dimensional array by just starting to study Java