红宝石+运算符是怎么做的? [英] How does ruby do the + operator?
本文介绍了红宝石+运算符是怎么做的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby不支持像variable++
这样的递增变量.我看到了以下行为:
Ruby does not support incrementing variables like variable++
. I saw this behaviour that:
2 ++ 4
给出6
.实际上,两个变量之间的任意数量的+
符号都被视为一个单独的+
.红宝石如何管理它?既然ruby做到了,那可以作为++
运算符不可用的原因吗?
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?
推荐答案
此:
2 ++ 4
解析为:
2 + (+4)
所以第二个+
是一元加号.添加更多加号只会添加更多一元+
运算符,因此:
so the second +
is a unary plus. Adding more pluses just adds more unary +
operators so:
2 ++++++ 4
被视为:
2 + (+(+(+(+(+(+4))))))
如果在Fixnum
中提供了+@
方法:
class Fixnum
def +@
puts 'unary +'
self
end
end
然后您甚至可以看到它的发生:
then you can even see it happen:
> 2 ++ 4
unary +
=> 6
这篇关于红宝石+运算符是怎么做的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文