Introduction
Hello and Welcome, readers! We hope you are doing great.
Ruby is an open-source, high-level, general-purpose programming language designed by Yukihiro Matsumoto in the mid-1990s. If you want to learn about Ruby, check out our articles on Ruby.
Did you ever get confused between the Unary and Binary + and - operators in Ruby? Don't worry. You are in the right place.
Today, In this blog, we will closely look into the Unary Plus(+) and Minus(-) Operators in Ruby with proper explanation and implementation. You will get a clear idea about these operators in Ruby from this article, so follow the article till the end.
So, without further ado, let's start our discussion.
Unary Operators
In Ruby, the unary operators are the operators that take only a single argument as a receiver. Boolean NOT(!), Bitwise Complement(~), Unary Plus(+) and Unary Minus(-) are some of the examples of Unary operators in Ruby.
This article will only consider the Unary Plus(+) and Unary Minus(-) operators. Don't get confused with the Binary Plus(+) and Binary(-) operators. Though they look similar, there is a considerable difference between them. The binary operators deal with two arguments, whereas the unary operators only deal with a single argument.
For example,
Unary - on 2 (-2), binary + on 1 and 2 (1 + 2)
Let's now discuss the Unary - and + operators in detail.
Unary Minus(-) Operator
In Ruby, the Unary minus(-) operator changes the sign of its numeric argument. It is not the same thing as the binary - operator. The unary - operator only deals with a single argument used as a notation for the negative numbers like - on 5 (-5), whereas the binary - operator performs subtraction between two numbers like 5 - 3.
Example
a = 5
# using the Unary minus operation on a
b = -a
puts("The value of b = (-a): ")
puts(b)
Output
The value of b = (-a):
-5
Explanation
In the above example, we can see that we defined a variable named “a” with a value of 5, and the unary minus(-) operation on “a” changes it to “-a”. So the output is -5.
Unary Plus(+) Operator
The Unary Plus(+) operator in Ruby does not affect the numeric argument. It just simply returns the value of the argument as it is. Like Unary + on 5 returns 5. Simply, it does not have any effect. Rather, it is provided only for the symmetry with the unary - but we can redefine it, which we will discuss later.
As explained earlier, it is also not the same as the binary + operator. The binary + operator performs addition like 1 + 2.
The Unary + operator has a slightly higher precedence than the Unary - operator.
Example
a = 5
# using the Unary plus operation on a
b = +a
puts("The value of b = (+a): ")
puts(b)
Output
The value of b = (+a):
5
Explanation
In the above example, we can see that we defined a variable named “a” with a value of 5, and the unary plus(+) operation on “a” does not affect a. So the output is 5.