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
ではまた!