Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby expression evaluation: whitespace matters?

Imagine it's Jan 19. This will not be hard if you look at this question today.

Date.today
 => Thu, 19 Jan 2012    # as expected

Date.today + 1
 => Fri, 20 Jan 2012    # as expected

Date.today+1
 => Fri, 20 Jan 2012    # as expected

Date.today +1
 => Thu, 19 Jan 2012    # ?!

What am I missing here?

like image 640
Kevin Davis Avatar asked Jan 19 '12 10:01

Kevin Davis


People also ask

Does white space matter in Ruby?

Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.

How do you check whitespace in Ruby?

If you are using Rails, you can simply use: x. blank? This is safe to call when x is nil, and returns true if x is nil or all whitespace.


1 Answers

The difference is that:

Date.today + 1 

is an addition of two numerical values and

Date.today +1 

is a call to the method today with the parameter sg(day of calendar reform) with value +1

The best way to examine this is to monkey patch the original method with debug output included. See this script as example:

require 'date'

class Date

  def self.today(sg=ITALY)
     puts "ITALY default("+sg.to_s+")" if sg==ITALY
     puts sg unless sg==ITALY
     jd = civil_to_jd(*(Time.now.to_a[3..5].reverse << sg))
     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end

end

puts "- Addition:"
Date.today + 1
puts "- Parameter:"
Date.today +1

This will print the following console output:

- Addition:
ITALY default(2299161)
- Parameter:
1
like image 103
fyr Avatar answered Sep 23 '22 05:09

fyr