DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

start each_with_index from 1 (This is good for UI)

👍 Usual way

books.each_with_index do |book, index|
  puts "#{index}: #{book.title}"
end

#=> 0: a
#=> 1: b
#=> 2: c

🦄 Start from 1

You can use each.with_index(1).

This is good when you use each method in .erb file. Because users want to see index from 1 usually.

books.each.with_index(1) do |book, index|
  puts "#{index}: #{title}"
end

#=> 1: a
#=> 2: b
#=> 3: c

🔗 Parent Note

Top comments (0)