本記事では初心者の私がrailsで新たに学習した
「each_with_index、each.with_index」
の意味と使い方についてアウトプットして参ります。
この記事を読むと、これらの2つのメソッドの違い、使い方を理解できます。
each_with_index、each.with_indexの違いと使い方
この2つのメソッドはどちらも
配列の要素を順番に取り出しているメソッドです。
food = [noodle, pasta, bread]
#配列foodを用意
food.each_with_index do |food_name, i|
put "#{i}番目に食べたのは#{food_name}です"
#結果
0番目に食べたのはnoodleです
1番目に食べたのはpastaです
2番目に食べたのはbreadです
のようになります。
ただ、each_with_indexは0から始まるため1から始めるのには
put "#{i+1}番目に食べたのは#{food_name}です"
としなければなりません。
一方each.with_indexメソッドを使うと、より簡単に好きな数から配列の番号を始めることができます
使い方
配列名.each.with_index(開始させたい値) do |item, i|
例
food = [noodle, pasta, bread]
#配列foodを用意
food.each_with_index do |food_name, i|
put "#{30}番目に食べたのは#{food_name}です"
#結果
30番目に食べたのはnoodleです
31番目に食べたのはpastaです
32番目に食べたのはbreadです
以上です。