问题
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?
回答1:
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
回答2:
Instead of ++ use += Example: a=2 a+=3 puts a
5
来源:https://stackoverflow.com/questions/24523329/how-does-ruby-do-the-operator