Search code examples
rubyunary-operator

what is the difference between += and =+ in ruby?"


The += and =+ is not working as I would expect. The following code outputs the correct value for @@num_things.

   class Thing
     @@num_things = 0 # class variable

     def initialize()
       @@num_things += 1 # increment @@num_things
     end

     def value
       @@num_things
     end

   end

   t1 =Thing.new()
   puts t1.value
   t2 =Thing.new()
   puts t2.value
   t3 =Thing.new()
   puts t3.value

The output is :

   1
   2
   3

However, if you invert the expression from += to be =+ now the output becomes

   1
   1
   1

What am i missing? I would expect the output to be the same in both cases once the value is called.


Solution

  • There's no such token as =+; it's actually two tokens: assignment followed by the unary + operator; the latter is essentially a no-op, so @@num_things =+ 1 is equivalent to @@num_things = 1.

    Since there is a += token, the language parser will parse it as a single token.

    (In the early formulations of BCPL which was the precursor to C, the modern -= operator was written as =-.)