67
57

More than 5 years have passed since last update.

each_with_index の index 値を 0 以外から開始させたい

Last updated at Posted at 2013-06-12

each_with_index で index の値を利用する時、
たとえば 0 ではなく 1 から使いたい場合…

%w(杏子 さやか マミ).each_with_index {|magica, i| puts "#{i + 1} #{magica}" }

# 1 杏子
# 2 さやか
# 3 マミ

とわざわざ +1 を書いたりするのはなんか面倒だ (´・ω・`)

そんなときは Enumerator#with_index(offset = 0) の出番!
見ての通り、offset 値に任意の数値を指定できるのだ!

Array#each をブロックなしで呼ぶと、Enumerator 型のオブジェクトが返ってくるので、
そいつに with_index を呼んでやる。
パッと見、each_with_index に見間違えそうなくらい、そっくりに書けるのが (個人的には) COOL♪

%w(杏子 さやか マミ).each.with_index(1) {|magica, i| puts "#{i} #{magica}" }

# 1 杏子
# 2 さやか
# 3 マミ

ちなみに Ruby 1.8.7 では with_index メソッドの引数で offset を指定することができないため、
この手法は使えません。

67
57
3

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
67
57