How to increment counter in Ruby loop

Tintin81 picture Tintin81 · Sep 21, 2013 · Viewed 9.1k times · Source

For my Rails application I am trying to build a rake task that will populate the database with 10 invoices for each user:

def make_invoices
  User.all.each do |user|
    10.times do
      date = Date.today
      i = user.invoices.create!(:number => user.next_invoice_number,
                                :date   => date += 1.year)
      i.save
    end
  end
end

How can I increment the date by one year?

Answer

Matthias picture Matthias · Sep 21, 2013

Change your loop to:

10.times do |t|
   puts t + 1 # will puts 1,2,3,4,5,6,7,8,9,10
end

And now you can set your year.