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 1 year has passed since last update.

eachの練習

Last updated at Posted at 2023-06-17

植物の名前と値段が入った配列がある。

plants_price = [["朝顔", [200, 250, 320]], ["向日葵", [300, 320, 480]], ["蘭", [7000, 9500]]]
#出力
朝顔の合計金額は770円です
向日葵の合計金額は1100円です
蘭の合計金額は16500円です

この配列を用いて、植物の名前とそれぞれの合計額が出力される
コードを作ろう。

こうなる。

plants_price = [["朝顔", [200, 250,320]], ["向日葵", [300,320,480]], ["蘭", [7000, 9500]]]
plants_price.each do |plant|
  sum = 0
  plant[1].each do |price|
    sum += price
  end
  puts "#{plant[0]}の合計金額は#{sum}円です"
end

plants_priceから"朝顔", [200, 250, 320]という値を取り出し、変数plantに代入する。

その後、自己代入しながらsumを出す。

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?