rubyでeach_with_indexでindexの値を0以外から始める方法
rubyでeach x indexをしたいパターンが多いです。
そのために、each_with_index
というメソッドがあります。
each_with_index
こちらは基本的に初期値が0からになります。
array = %w(foo bar baz) array.each_with_index do |x, index| puts "#{index}番目#{x}" end => 0番目foo 1番目bar 2番目baz
1から始めたいという場合は、下記のようにすることで回避できます。
array = %w(foo bar baz) array.each_with_index do |x, index| puts "#{index + 1}番目#{x}" end => 1番目foo 2番目bar 3番目baz
ただ、いちいち+ n
を書かないといけないので、めんどくさいです。
each.with_index
そこで、each.with_index
を使用します。
こちらは()を入れることで開始位置を指定できます。
array = %w(foo bar baz) array.each.with_index(1) do |x, index| puts "#{index}番目#{x}" end => 1番目foo 2番目bar 3番目baz
まとめ
indexを0から始める場合は、each_with_index
0以外から始める場合は、each.with_index(n)
をするのがいいのかなと個人的には思いました。