How does ruby do the + operator?

大城市里の小女人 提交于 2020-02-24 20:39:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!