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)