In this article, as a beginner, I learned anew with rails 「each_with_index、each.with_index」 I will output about the meaning and usage of.
Read this article to understand the differences between these two methods and how to use them.
Both of these two methods This method retrieves the elements of the array in order.
food = [noodle, pasta, bread]
#Prepare array food
food.each_with_index do |food_name, i|
put "#{i}The second one I ate#{food_name}is"
#result
The 0th thing I ate was noodle
The first one I ate was pasta
The second one I ate was bread
It looks like.
However, each_with_index starts from 0, so to start from 1
put "#{i+1}The second one I ate#{food_name}is"
Must be.
On the other hand, the each.with_index method makes it easier to start the array number from any number you like.
How to use
Array name.each.with_index(The value you want to start) do |item, i|
Example
food = [noodle, pasta, bread]
#Prepare array food
food.each_with_index do |food_name, i|
put "#{30}The second one I ate#{food_name}is"
#result
The 30th thing I ate was noodles
The 31st thing I ate was pasta
The 32nd thing I ate was bread
that's all.
Recommended Posts