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.

Ruby13

Last updated at Posted at 2023-02-03

問題

以下のように、果物の名前と値段が入った配列があります。
この配列を用いて、果物の名前とそれぞれの合計額が出力される
コードを記述してください。

fruits_price = [["apple", [200, 250, 220]], ["orange", [100, 120, 80]], ["melon", [1200, 1500]]]
ターミナル
appleの合計金額は670円です
orangeの合計金額は300円です
melonの合計金額は2700円です



模範解答

模範解答
fruits_price = [["apple", [200, 250, 220]], ["orange", [100, 120, 80]], ["melon", [1200, 1500]]]

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

【解説】

3行目
fruits_priceから["apple", [200, 250, 220]]という値を取り出す。変数fruitに代入します。

4行目〜7行目
fruitの1番目の値[200, 250, 220]から値を1つずつ取り出す。自己代入しながらsumを出力します。
以降、オレンジとメロンも順に取り出し処理は同様です。

補足として・・・添字1は金額、添字0は果物です。

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?