This article uses Ruby 2.6.5 installed on macOS Catalina 10.15.6. I've summarized them to distinguish between the two.
each_with_index --Each_with_index and __ By passing two values __ to a block variable, you can iterate as many times as there are elements in the __ array __ and __ to indicate what number that element is.
fruits = ["apple", "banana", "peach"]
fruits.each_with_index do |fruit, index|
puts "#{index}The second fruit is#{fruit}is."
end
However, if this is left as it is, it will be "The 0th fruit is apple."
The 0th fruit is apple.
The first fruit is banana.
The second fruit is peach.
each.with_index --I put 1__ in the argument of __index. --Then, the number assigned to the element will start from 1.
fruits.each.with_index(1) do |fruit, index|
puts "#{index}The second fruit is#{fruit}is."
end
As you can see, the order starts from 1 neatly.
The first fruit is apple.
The second fruit is banana.
The third fruit is peach.
Recommended Posts