LoginSignup
90
89

More than 5 years have passed since last update.

each_with_indexの使い方

Last updated at Posted at 2018-03-26

eachループで回しつつ、それぞれのデータに番号を振りたいと思うとき、どうすればいいんだろうとググったら、便利なeach_with_indexメソッドに出くわしたので、まとめました。

each_with_indexメソッドの使い方

配列.each_with_index do |item, i|
 "#{i}番目のデータは、#{item}"です。
end

(例)フルーツ名が格納された配列を順番に表示する場合

fruit = ["りんご", "みかん", "いちご"]
fruit.each_with_index do |item, i|
 "#{i}番目のフルーツは、#{item}"です。
end

結果

0番目のフルーツは、りんごです。
1番目のフルーツは、みかんです。
2番目のフルーツは、いちごです。

indexは、0から始まります。
1から番号を始めたい場合は、"#{i+1}番目のフルーツは、#{item}"です。
という感じで、単純にii+1にすればいい。

開始したい番号を指定するeach.with_indexメソッド

10から番号をつけたいという場合は、上の例でいくと、

fruit.each.with_index(10) do |item, i|
 "#{i}番目のフルーツは、#{item}"です。
end

結果

10番目のフルーツは、りんごです。
11番目のフルーツは、みかんです。
12番目のフルーツは、いちごです。
90
89
1

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
90
89