Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 554
Mladen Jablanović Avatar asked Apr 15 '11 17:04

Mladen Jablanović


People also ask

What is the use of unary plus operator?

The unary plus operator ( + ) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

Does += works in ruby?

+= works in Ruby like it does in so many other programming languages. y =+ x is the same as y = +x is the same as y = x . Ruby sees =+ as two operators, not one. This also holds for negative values of x , too.

What is unary operator in Ruby?

In Ruby, a unary operator is an operator which only takes a single 'argument' in the form of a receiver. unary operator likes + - ! ~ & * ..

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.


2 Answers

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.

like image 76
Matt Ball Avatar answered Nov 15 '22 23:11

Matt Ball


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

like image 31
DirtyF Avatar answered Nov 15 '22 23:11

DirtyF