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?
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.
+= 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.
In Ruby, a unary operator is an operator which only takes a single 'argument' in the form of a receiver. unary operator likes + - ! ~ & * ..
=~ 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With