Ruby Tuesday – Date#-

Today’s Ruby Tuesday is on Date#-.

Date#- returns the difference between two dates if passed a Date object. The difference is expressed as a rational number, as this method is also available on DateTime objects as well.

Date.new(2015, 4, 21) - Date.new(1999, 12, 31)
# => (5590/1)
Date.new(2015, 4, 21) - Date.new(1999, 4, 20)
# => (5845/1)
Date.new(2015, 4, 21) - Date.new(2015, 4, 20)
# => (1/1)
Date.new(2015, 4, 21) - Date.new(2015, 4, 23)
# => (-2/1)

If a numeric value is passed to Date#- it returns a Date object that is that many days of a difference.

Date.new(2015, 4, 21) - 1
# => #<Date: 2015-04-20 ((2457133j,0s,0n),+0s,2299161j)>
Date.new(2015, 4, 21) - 365
# => #<Date: 2014-04-21 ((2456769j,0s,0n),+0s,2299161j)>
Date.new(2015, 4, 21) - (1/2)
# => #<Date: 2015-04-21 ((2457134j,0s,0n),+0s,2299161j)>
Date.new(2015, 4, 21) - (2/2)
# => #<Date: 2015-04-20 ((2457133j,0s,0n),+0s,2299161j)>

Date#- will not only accept positive numeric values, but also negative values, and will result with a day that is in the future.

Date.new(2015, 4, 21) - -1
# => #<Date: 2015-04-22 ((2457135j,0s,0n),+0s,2299161j)>

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *