LoginSignup
2
0

More than 5 years have passed since last update.

配列を繰り返し処理する際にindexが欲しい場合【each.with_index】

Last updated at Posted at 2019-03-30

はじめに

本項ではeach.with_indexについて解説

概要

要素にインデックスを添えて繰り返すメソッド。
要素自体に順番を示すインデックスを属性として設定していないが、処理として要素の順番を示したい場合に使用する。

使用方法

参考例.rb
Objs.each.with_index(offset){|obj,index| 〜繰り返す処理〜 }

# Objs => 繰り返す対象の配列。
# offset => 開始するインデックス番号。
# obj => 繰り返し処理中の要素の変数名。
# index => 繰り返し処理中のインデックスの変数名。

備考
- offsetを与えない場合、indexは0から始まります。

使用例(offsetなし)

使用例(offsetなし).rb
animals = ["cat","dog","mouse"]

animals.each.with_index {|animal,i|
  puts "#{i}番目は#{animal}です。"
}

出力結果は以下

0番目はcatです
1番目はdogです
2番目はmouseです

使用例(offsetあり)

人間の感覚で0から始まると気持ちが悪いのでoffsetに1を与えると良いと思います。

使用例(offsetあり).rb
animals = ["cat","dog","mouse"]

animals.each.with_index(1) {|animal,i|
  puts "#{i}番目は#{animal}です。"
}

出力結果は以下

1番目はcatです
2番目はdogです
3番目はmouseです

参考記事

class Enumerator (Ruby 2.6.0)

※修正(2018/3/31)
each_with_index (Enumerable) - Rubyリファレンス
上記のリンクはeach_with_indexのものでした。失礼しました。ご指摘ありがとうございます。
またご指摘いただいたscivolaさんの両メソッドの解説がわかりやすい為、引用させていただきます。

(前略)each.with_index と each_with_index は見た目は似ていますが,別物なんですよね。
each_with_index は Enumerable モジュールのメソッドです。オフセットを与えることはできません。
一方,each.with_index のほうは,ブロック無しの each が Enumerator オブジェクトを返し,それの with_index メソッドを呼んでいます。
Enumerator はちょっと抽象的で分かりにくいものですが,それの理解が鍵ですね。

内容のみならず、レイアウトや書き方にアドバイスがある方はお気軽に(優しく)コメントを頂けると助かります。

2
0
2

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