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.

配列における計算と出力

Posted at

問題

八百屋さんのシステムで以下の配列から名前と合計金額を出力するプログラムを描いてください

fruits_price = [["banana", [200, 250, 220]], ["grape", [100, 120, 80]], ["watermelon", [1200, 1500]]]

解答

fruits_price.each do |name, price|
  puts "#{name}は合計金額は#{price.sum}円です"
end

each文により配列から順に値を取り出してnameとpriceに入れます。
それを出力する際にprice.sumで値を全て合計してから出力をしています。
これにより出力結果が以下のようになります。

ターミナル
bananaの合計金額は670円です
grapeの合計金額は300円です
watermelonの合計金額は2700円です
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?