Search code examples
rubyunary-operator

Ruby operator "+" behavior varies depending on spacing in code?


I came across a bit of an oddity (am using Ruby 1.9.1). Case scenario being:

class D
    ...
    def self.d6
        1+rand(6)
    end
    ...
end

v = D::d6+2    # fine and dandy
v = D::d6 +2   # in `d6': wrong number of arguments (1 for 0) (ArgumentError)
v = D::d6 + 2  # fine and dandy

Why the "+2" in second case is treated as being "positive 2" and not an "addition of 2"?


Solution

  • The + same as the - in ruby are overloaded in order to make the syntax look nice.

    When there is no space the Ruby parser recognizes the + as the method which is called on the result of d6 which is an Integer. Same goes for the version with space before and after the +.

    However: In the operator precedence in Ruby + as a unary operator is defined before + as a binary operator (as is often the case in other languages as well).

    Therefore if there is a space before the + but not after it, the Ruby Parser will recognize it as d6(+2) which fits the error message.