AshwinKumarS
AshwinKumarS

Reputation: 1313

How does ruby do the + operator?

Ruby does not support incrementing variables like variable++. I saw this behaviour that:

2 ++ 4

gives 6. In fact, any number of + signs between two variables are treated as one single +. How does ruby manage that? And since ruby does that, can it be taken as the reason for the unavailability of the ++ operator?

Upvotes: 2

Views: 94

Answers (2)

mu is too short
mu is too short

Reputation: 434585

This:

2 ++ 4

is parsed as:

2 + (+4)

so the second + is a unary plus. Adding more pluses just adds more unary + operators so:

2 ++++++ 4

is seen as:

2 + (+(+(+(+(+(+4))))))

If you provide your +@ method in Fixnum:

class Fixnum
  def +@
    puts 'unary +'
    self
  end
end

then you can even see it happen:

> 2 ++ 4
unary +
 => 6 

Upvotes: 9

max
max

Reputation: 10444

Instead of ++ use += Example: a=2 a+=3 puts a

5

Upvotes: 0

Related Questions