1
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 1 year has passed since last update.

【学習】Ruby:each と each_with_index そして each.with_index の違い

Posted at

はじめに

アルゴリズム問題を解く中で、Rubyのメソッドには似ているけどちょっとだけ違うものがあることを学びました。
今回はその中でもeach,each_with_index, そしてeach.with_indexについて。

1. each メソッドとは?

each は、配列やリストの要素を一つずつ取り出して処理を行うための基本的なメソッドです。

fruits = ["apple", "banana", "cherry"]

fruits.each do |fruit|
  puts fruit
end

👇出力結果

apple
banana
cherry

👇説明
each は配列の中の要素を一つずつ取り出し、それをブロック内で処理します。この場合、fruit には配列の各要素が順番に入ります。
fruitabといったほかの変数で置き換え可能です。
その場合puts fruitの部分もputs aというように変更することになります。

2. each_with_index メソッドとは?

each_with_index は、each に加えて 要素のインデックス(位置)も一緒に取得できます。

fruits.each_with_index do |fruit, index|
  puts "#{index}: #{fruit}"
end

👇 出力結果

0: apple
1: banana
2: cherry

👇 説明
each_with_index は2つのブロック引数を使います

  • 1つ目の引数:要素(fruit
  • 2つ目の引数:インデックス(index
    このインデックスは、0から始まる点に注意してください!

3. each.with_index メソッドとは?

一見似ていますが、each.with_index は少し特殊です。
このメソッドは each にインデックス機能を後付けする ようなイメージです。

fruits.each.with_index do |fruit, index|
  puts "#{index}: #{fruit}"
end

👇 出力結果

0: apple
1: banana
2: cherry

👇 説明
each.with_index の動きは each_with_index に似ていますが、異なる点があります

  1. 他のメソッドにもインデックスを適用可能with_indexeach に限らず、mapselect など他の Enumerator にも使えます。
  2. 柔軟性が高いwith_index は引数をとって、インデックスの開始番号をカスタマイズすることも可能です。

4. each.with_indexでインデックスのカスタマイズ

each.with_indexインデックスの開始番号 を変更できる便利な機能があります。

fruits.each.with_index(1) do |fruit, index|
  puts "#{index}: #{fruit}"
end

👇 出力結果

1: apple
2: banana
3: cherry

👇 説明
with_index(1) のように引数を渡すと、インデックスは 1 から始まります‼

まとめ

メソッド インデックス取得 インデックスの開始番号変更
each
each_with_index
each.with_index

each_with_index はシンプルに使えるため、基本的な場面で便利です。
一方で、each.with_index は柔軟性が高く、より高度な操作が必要なときに役立つという事を知ることができました。
今回はこれで以上になります。

👇参考記事

1
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
1
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?