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)