0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

eachの入れ子構造

Posted at

同じ果物でも高級と言われるもの、大きさ、見切り品など金額が変わってきます。
そのような計算をしていきたいと思います。

fruits_price = [["りんご", [200, 250, 220]], ["オレンジ", [100, 120, 80]], ["ぶどう", [1200, 1500]]

今回は配列のなかに配列が入っており、果物の名前とそれぞれの合計額を出力します。

初めにeach文を使用してそれぞれの果物を一つずつ取り出します。また合計金額を足していくための処理の記述をします。

fruits_price = [["りんご", [200, 250, 220]], ["オレンジ", [100, 120, 80]], ["ぶどう", [1200, 1500]]

fruits_price.each do |f|
  sum = 0
end

この記述で、

["りんご", [200, 250, 220]
["オレンジ", [100, 120, 80]
["ぶどう", [1200, 1500]

という形で取り出せるようにします。
次にそれぞれの果物の金額を足していく処理を記述していきます。

f[1].each do |p|
  sum += p
end

fの1番目の値[200, 250, 220]から値を1つずつ取り出して、自己代入をしながら最後にsumを出力します。

最終的な記述は、

fruits_price = [["りんご", [200, 250, 220]], ["オレンジ", [100, 120, 80]], ["ぶどう", [1200, 1500]]

fruits_price.each do |f|
  sum = 0
  f[1].each do |p|
    sum += p
  end
  puts "#{f[0]}の合計金額は#{sum}円です"
end

ちなみにf[0]は、[りんご]、[オレンジ]、[ぶどう]、f[1]は、[200, 250, 220]、 [100, 120, 80]、[1200, 1500]が入っていて、りんごの処理が終わったらオレンジ、ぶどうの順番で処理を処理を行っていきます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?