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
[Ruby] Get array elements alternately.
Array
How to divide a two-dimensional array into four with ruby
Learning Ruby with AtCoder 13 How to make a two-dimensional array
Sorting hashes in a Ruby array
[Ruby] Extracting double hash in array
Explanation about Array object of Ruby
What is a Ruby 2D array?
Ruby learning 4
[Java] array
Java array
Array practice
Ruby learning 5
Java array
Ruby basics
java (array)
Ruby Review 2
Ruby addition
Refactoring Ruby
Java array
Ruby learning 3
Array practice 2
Ruby setting 2
Java array
Ruby problem ⑦
Ruby learning 2
[Ruby] Get unique elements from an array
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
12 of Array
Ruby settings 1
Refactoring Ruby
java array
Sort an array of Ruby homebrew classes
[Java] Array
Ruby basics
Ruby memo
Ruby learning 1
Ruby Review 1
[Ruby] Module
[Ruby] Calculation by extracting elements from an array
Two-dimensional array by just starting to study Java