What's the point of unary plus operator in Ruby?

ぐ巨炮叔叔 提交于 2019-11-26 21:49:00

问题


Apart from making a nice symmetry with unary minus, why is unary plus operator defined on Numeric class? Is there some practical value in it, except for causing confusion allowing writing things like ++i (which, unlike most non-Rubyists would think, doesn't increment i).

I can think of scenario where defining unary plus on a custom class could be useful (say if you're creating some sexy DSL), so being able to define it is ok, but why is it already defined on Ruby numbers?


回答1:


Perhaps it's just a matter of consistency, both with other programming languages, and to mirror the unary minus.

Found support for this in The Ruby Programming Language (written by Yukihiro Matsumoto, who designed Ruby):

The unary plus is allowed, but it has no effect on numeric operands—it simply returns the value of its operand. It is provided for symmetry with unary minus, and can, of course, be redefined.




回答2:


One possible reason I see is to explicitly state that a number is positive(even though it by default is positive).

ruby-1.9.2-p136 :051 > +3
 => 3 
ruby-1.9.2-p136 :052 > 3
 => 3 



回答3:


As mentioned in the docs, if a string is frozen the unary plus operator will return a mutable string.



来源:https://stackoverflow.com/questions/5680587/whats-the-point-of-unary-plus-operator-in-ruby

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