Reputation: 15
Is there something similar to the code below in Ruby where X stands for the number of months to add to today's date but is coming from a variable
Time.zone.today + X.month ## X comes from a variable
Preferably without using a loop as 'm' can be large number in the example below
def add_months_to_today(m)
number_of_months_to_add = m.to_i
return_date = Time.zone.today
if m.to_i > 0
(1..number_of_months_to_add).each do |i|
return_date = return_date + 1.month
end
end
return_date
end
Upvotes: 1
Views: 522
Reputation: 114248
Your code works perfectly fine:
x = 4
Time.zone.today + x.month
#=> Sun, 29 Sep 2019
month
is a method defined on Integer
. It doesn't matter if the integer is given as a literal or as a variable. The receiver just has to be an Integer
.
Instead of Time.zone.today
you could also call Date.current
:
Date.current + 4.month #=> Sun, 29 Sep 2019
Rails also adds a variety of other methods to Date
: (also via DateAndTime::Calculations
)
Date.current.advance(months: 4) #=> Sun, 29 Sep 2019
Date.current.months_since(4) #=> Sun, 29 Sep 2019
4.months.since(Date.current) #=> Sun, 29 Sep 2019
The above also work for instances of Time
:
Time.current.advance(months: 4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
Time.current.months_since(4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
4.months.since #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
When only dealing with dates, Ruby's built-in >>
or next_month
might be used as well:
Date.current >> 4
#=> Sun, 29 Sep 2019
Date.current.next_month(4)
#=> Sun, 29 Sep 2019
Note that you can use 4
and x
interchangeably in all of the above examples.
Upvotes: 4