开发者

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

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 wo开发者_运维百科uld 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?


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.


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


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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜