0
0

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 3 years have passed since last update.

each_with_indexとeach.with_indexの違いを理解する

Last updated at Posted at 2020-12-21

◆each_with_indexの場合

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

#以下の様に出力されます
# 0:Ruby
# 1:PHP
# 2:Python

◆each.with_indexの場合

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

# 1:Ruby
# 2:PHP
# 3:Python

今までeach_with_indexを使って、わざわざ"index+1"として1から表示してたけど、
each.with_indexは1以外でも指定の数字から始められるので便利!

0
0
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?