Why is the addition "operator" a method while the assignment operator += not?
Why do operators work this way:
ruby-head > 2.+(4)
=> 6
While assignment operators work this way:
ruby-head > i = 1
=> 1
ruby-head > i += 1
=> 2
ruby-head > i.+=(1) SyntaxError: (irb):26: syntax error, unexpected '=' i.+=(1) ^ from /Users/fogonthedowns/.rvm/rubies/ruby-head/bin/irb:17:in `'
Because assignment works on variables not objects and thus cannot be implemented as a method.
The += is (as I conjectured) syntactic sugar that uses the + method. If you subclass or monkey-patch a class to change the behaviour of +:
class CustomPlus
  attr_accessor :value
  def initialize(value)
    @value = value
  end
  def +(other)
    value + other * 2
  end
end
Then the result is this:
ruby-1.9.1-p378 > a = CustomPlus.new(2)
 => #<CustomPlus:0x000001009eaab0 @value=2> 
ruby-1.9.1-p378 > a.value
 => 2 
ruby-1.9.1-p378 > a+=2
 => 6 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With