0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby] each_with_index と each.with_indexの違いを考えた

Posted at

この記事ではmacOS Catalina10.15.6にインストールしたRuby 2.6.5を使っています。
2つの違いを区別するためにまとめてみました。

each_with_index

  • each_with_indexと__2つの値__をブロック変数に渡すことで、__配列の要素の数だけ繰り返し処理__と__その要素が何番目のものか表す__ことができます。
fruits = ["apple", "banana", "peach"]

fruits.each_with_index do |fruit, index|
  puts "#{index}番目のフルーツは#{fruit}です。"
end

結果

ただ、このままだと「0番目のフルーツはappleです。」となってしまいますね。

0番目のフルーツはappleです。
1番目のフルーツはbananaです。
2番目のフルーツはpeachです。

each.with_index

  • __indexの引数に1__を入れました。
  • すると、要素に割り振られる番号が1からスタートになります。
fruits.each.with_index(1) do |fruit, index|
  puts "#{index}番目のフルーツは#{fruit}です。"
end

結果

この通り、きれいに1から順番が始まっていますね。

1番目のフルーツはappleです。
2番目のフルーツはbananaです。
3番目のフルーツはpeachです。
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?