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

3

11

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?

Duenna answered 15/4, 2011 at 17:58 Comment(0)
K
9

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.

Karmakarmadharaya answered 15/4, 2011 at 18:19 Comment(0)
O
7

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

Odell answered 22/10, 2018 at 12:35 Comment(2)
Thanks, nice to know. The question was about the Numeric class though.Agreed
Came here looking for the unary plus in connection with String, even though the question was about Numeric.Kehoe
W
1

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 
Woven answered 15/4, 2011 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.