The effect of outgoing space after '-' in a Ruby expression

Today I tried something in the Rails console, and it happened,

2.0.0p247 :009 > Date.today -29.days => Fri, 07 Feb 2014 2.0.0p247 :010 > Date.today - 29.days => Thu, 09 Jan 2014 

I'm pretty puzzled. I see that I am missing something basic. But it just amazes me! Can anyone explain why this is happening?

+6
source share
2 answers

This actually happens:

 Date.today(-29.days) # => Fri, 07 Feb 2014 

today has an optional parameter called start , which defaults to Date::ITALY .

An additional argument is the day of the calendar reform (beginning) as the Julian of the day number, which should be from 2298874 to 2426355 or - / + oo. The default value is the date :: ITALY (2299161 = 1582-10-15).

Passing -29.days to today does not seem to have an effect.

While:

 Date.today + -29.days # => Thu, 09 Jan 2014 

This is the same as:

 Date.today - 29.days # => Thu, 09 Jan 2014 
+4
source

The Fixnum#days method is defined in the ActiveSupport library in Rails . More specifically, it is defined in the module active_support / core_ext / numeric / time

Just load ActiveSupport inside the console

 > require 'active_support' true > require 'active_support/core_ext' true > 29.days => 2505600 > -29.days => -2505600 

The days method code is as follows:

 def days ActiveSupport::Duration.new(self * 24.hours, [[:days, self]]) end 

The self object in this case is 29 or -29 . This is multiplied by 2505600, which is a legitimate calculation and returns the number of seconds that the number 29 represents.

Given this, in the first calculation, you simply pass two objects to the console input, the first of which is a Date object, and the second is a number. Similar to sending the following message:

 > puts "test" 

That is, -29.days is passed as an argument to the object returned by Date.today . And Date.today takes a parameter that defines the day the calendar starts. Refer to this answer for the days accepted . If any unrecognized parameter is passed, the default start date is used (which is Date :: GREGORIAN)

 > Date.today => Thu, 09 Feb 2014 > Date.today Date::JULIAN => Fri, 25 Jan 2014 

So, Ruby checks to see if you were transferred on a valid start date or not, and decide on a start date. For this reason, you still get the date today as an answer when you execute the first command.

The second command is simply subtracting one Date object from another, which is understood by Ruby as the number of seconds you want to subtract from today's date. 29.days internally converted to number of seconds in both cases.

Hope this helps.

+2
source

All Articles