0
0

More than 3 years have passed since last update.

each.with_indexで番号をつけよう! ❏Ruby❏

Last updated at Posted at 2019-12-07
sample.rb
fruits = ["バナナ","りんご","みかん","パイナップル"]

fruits.each.with_index(1) do |fruit, index|
  puts "(#{index}): #{fruit}"
end

出力結果
(1): バナナ
(2): りんご
(3): みかん
(4): パイナップル

()の中から始まる数字を順番に振ってくれます。
||の中の第2引数に変数を入れます。



似たものに each_with_indexがありますが、必ず0から始まるので使い勝手がイマイチです。

個人的な意見としては、好きな数字から始められる each.with_indexに軍配が上がります。



参考

https://shirusu-ni-tarazu.hatenablog.jp/entry/2012/11/04/173513
https://qiita.com/gestalt/items/d2c663b4be524581747e



ではまた!

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