LoginSignup
41

More than 3 years have passed since last update.

posted at

updated at

each_with_indexとeach.with_index

each_with_indexの場合

array = ["Ruby", "PHP", "Python"]
array.each_with_index do |element, index|
  p "#{index}#{element}"
end

#以下の様に出力
0Ruby
1PHP
2Python

each.with_indexの場合

array = ["Ruby", "PHP", "Python"]
array.each.with_index(1) do |element, index|
  p "#{index}#{element}"
end

1Ruby
2PHP
3Python

indexを指定の数字から始めたいときに便利

参考

【Ruby】each_with_indexは知ってたけどeach.with_indexは知らなかった… - 訳も知らないで

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
What you can do with signing up
41