with_indexについて

便利メソッドの紹介です。

railsでユニークな値をつけたいときには、with_indexを使えば簡単に実現できます。

pepole = %w(Bob Tom Lazy)
pepole.each.with_index do |name, index|
  p "#{index}:#{name}" => "0:Bob" "1:Tom" "2:Lazy"
end

each_with_indexでも可能です。

pepole.each_with_index do |name, index|
  p "#{index}:#{name}"
end

これをどのように使うかということです。 たとえば。Javascriptの操作をしたいときは、ユニークな値だと、対象を絞りやすくなります。

- @users.each_with_index do |user, index|
    span id="user_no#{index}"
    user.name

上記の使い方以外にも、mapやselectのように要素だけを繰り返すメソッドでも、使えることができます。

p pepole.select.with_index { |name, index| index > 0 } => ["Tom", "Lazy"]

まとめ

知っておけば、応用で使えそう。