Ruby's operators, like +
or *
, follow the order of precedence as in mathematics when used in the syntax-sugar form. In the following, *
is called before +
:
# Syntax-sugar form
5 + 5 * 2 # => 15
In the non-syntax-sugar form, the methods follow the linear order in which they are written. In the following, +
is called before *
:
# Non-syntax-sugar form
5.+(5).*(2) # => 20
Methods that I define, like the +
method as follows, work both with and without the syntax-sugar form:
class WackyInt
attr_reader :value
def initialize(value)
@value = value
end
def +(other)
WackyInt.new(value + other.value)
end
end
ONE = WackyInt.new 1
FIVE = WackyInt.new 5
# As operators
ONE + FIVE # => #<WackyInt @number=-4>
# As methods
ONE.+(FIVE) # => #<WackyInt @number=-4>
The defined operators follow the respective order of precedence both in the syntax-sugar form and the non-syntax-sugar form.
How can Ruby parse this?