🤖

【Ruby】 each_with_indexの使い方

2024/03/16に公開

使い方

array = ["パン"、"ご飯"]
array.each_with_index do |item, i|
 "#{i}番目のデータは、#{item}です。"
end

結果

0番目のデータは、パンです。
1番目のデータは、ご飯です。

開始したい数字を指定したい時

fruites = [“リンゴ”, “メロン”, “ブドウ”]

fruites.each.with_index(10) do |item, i|

puts “#{i}番目のフルーツは#{item}です。”

end

結果

10番目のフルーツはリンゴです。

11番目のフルーツはメロンです。

12番目のフルーツはブドウです。

Discussion