2
0

More than 3 years have passed since last update.

【rails】 each_with_index、each.with_indexの違いと使い方

Last updated at Posted at 2020-09-30

本記事では初心者の私が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です

以上です。

2
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
2
0