Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Assignment Operators

Tags:

ruby

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 `'

like image 968
JZ. Avatar asked Dec 12 '22 16:12

JZ.


2 Answers

Because assignment works on variables not objects and thus cannot be implemented as a method.

like image 106
sepp2k Avatar answered Jan 06 '23 13:01

sepp2k


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 
like image 28
Danny Staple Avatar answered Jan 06 '23 11:01

Danny Staple