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

主宰稳场 提交于 2019-11-28 01:03:50

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.

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 

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

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