LoginSignup
3
3

More than 5 years have passed since last update.

ブロックに渡されている要素のインデックスを取得する

Last updated at Posted at 2014-07-31

地味に考えてしまったのでメモ

array =[3,6,2,5,4,7]
array.each{|item|
    p array.index(item)
}

問題は配列がユニークじゃないと前にある要素が吐かれる

追記

「Rubyの配列はeachだよね!」という固定観念に囚われていたことに気付く.
Cでよくやるようにfor文でインデックスを使えばよかった.
Rubyならtimesメソッドとlengthメソッドがあるから楽チン.

array =[3,6,2,5,4,7]
array.length.each{|index|
    p array[index]
}

更に追記

そもそもRubyは要素とインデックス両方をブロックに渡せるメソッドがあることをコメントで教えて頂いた.
そりゃあるよね.

array =[3, 6, 2, 5, 4, 7, 2, 3, 4]
array.each.with_index do |value, index|
  p index => value
end
3
3
1

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
3
3