Chapter 6: Operators
Ruby supports all the operators you learned in high-school Maths, and many more. In this section, we’ll learn about operators in Ruby.
Let’s start with the simplest, and add two numbers, using the plus +
operator.
first_number = 10
second_number = 20
sum = first_number + second_number
print sum # prints 30
Nothing fancy here.
Actually, there is. Since Ruby is a pure object-oriented language, + is actually a method defined on all numbers, which adds the argument, i.e. second number and returns the result. But ignore that for now. We may come back to it later.
Similarly, Ruby supports -
, *
, and /
operators, which work as you expect. In addition, the =
operator we’ve been using so far assigns the value on the right hand side to the variable on the left.
Comparison Operators
You can compare two numbers using the less-than (<
), greater-than (>
), less-than-or-equal-to (<=
), and greater-than-or-equal-to (>=
) operators. All these operators return either true
or false
value.
3 < 5 # true
5 > 3 # true
num = 7
num <= 7 # true
num >= 7 # true
Equality Operators
To compare if two variables are equal or not, use the ==
and !=
operators .
a = 10
b = 10
c = 12
a == b # true
b == c # false
a != c # true
Ruby also provides a ===
operator, which depends on how and where it’s called. Don’t worry about it now, it will only add to confusion. We’ll revisit it later when it’s needed.
Logical Operators
Ruby has two specific values true
and false
which indicate whether an expression is true or false. I understand it might not make sense, but trust me that it will, once we see a few examples.
Most likely, you’ll be using &&
, ||
and !
operators with boolean values. This is how they work.
# Logical AND
true && true; # true
true && false; # false
false && true; # false
false && false; # false
# Logical OR
true || true; # true
true || false # true
false || true # true
false || false # false
# NOT
!true # false
!false # true
You can use any boolean expressions (expressions returning true
and false
) in place of true
and false
, and it works the same.
result = 5
(result > 3) && (result < 7) # true
(result == 0) || (result > 8) # false
That wraps up our brief exploration into Ruby’s operators.