3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Ruby】map.with_indexとeach_with_indexの違い

Last updated at Posted at 2021-12-07

map.with_index

配列などの要素にindexを添えることができるメソッド

[100, 200, 300].map.with_index do |n, idx|
  p [n, idx]
end

#=>  [[100, 0], [200, 1], [300, 2]]
  • with_index(1)で指定の数字からカウントできる
[100, 200, 300].map.with_index(1) do |n, idx|
  p [n, idx]
end

#=>  [[100, 1], [200, 2], [300, 3]]

each_with_index

[100, 200, 300].each_with_index do |n, idx|
  p [n, idx]
end
# => [100, 0]
#    [200, 1]
#    [300, 2]

3
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?