Operators in Ruby
Operators are essential components of Ruby that are used to manipulate data and combine basic expressions into more intricate ones. The fact that many operators in Ruby are implemented as methods, in contrast to many other languages, gives classes the ability to specify or modify their behaviour. Only a predetermined set of known operators can be utilized or redefined; you cannot, however, build completely new operators. Operators are reserved words or symbols that are used to combine simpler expressions into larger, compound expressions and to perform calculations on values.
The fact that many operators in Ruby are implemented as methods is an important feature. This indicates that executing an operation like as x + y
entails calling the +
method, internally expressed as x.+(y)
, on the object x
with y
as the argument. Classes can declare or alter the meaning of operators (operator overloading) with this approach. However, you are restricted to the predetermined set of recognized operators; you are unable to create additional ones.
In general, operators are categorized according to their associativity, precedence (which establishes the order of evaluation), and arity (number of operands: unary, binary, or ternary).
Operator Categories and Code Examples
Numerous categories of operators, many of which can be defined as methods (M=Y), are summarized in the following tables:
Arithmetic Operators (Binary)
Basic mathematical computations are carried out via these operators.
Operator | Operation | Example | Result |
+ | Addition (or Concatenation) | 1 + 2 | 3 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication (or Repetition) | 2 * 3 | 6 |
/ | Division | 10 / 2 | 5 |
% | Modulo (Remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 1024 | 2 to the power 1024 |
Code Example (Operator Overloading for Strings):
Strings and numbers respond differently to the +
and *
operators.
# Concatenation
puts "Ruby" + " rocks!"
# Repetition
puts "Ruby! " * 3
Output
Ruby rocks!
Ruby! Ruby! Ruby!
Unary Operators
One operand is taken by unary operators. It is necessary to use specific naming conventions when declaring these operators as methods: -@ for unary minus and +@ for unary plus.
Operator | Operation | Method Name | Example (Numeric) |
+ | Unary Plus | +@ | +10 (no effect on numeric operand) |
- | Unary Minus | -@ | -5 |
! | Boolean NOT | ! | !true |
~ | Bitwise Complement | ~ | ~5 |
Code Example (Defining Unary Operators):
class Foo
def -@
puts "unary minus"
end
def +@
puts "unary plus"
end
end
f = Foo.new
+f #=> "unary plus"
-f #=> "unary minus"
Output
unary plus
unary minus
Assignment Operators
=
is the basic assignment operator. Compound assignment operators, sometimes referred to as shortened assignment pseudooperators, are likewise supported by Ruby. These are abbreviations that use the matching binary operator to expand into a regular assignment.
Operator | Assignment Expansion | Example | Equivalent to |
= | Simple Assignment | x = 1 | – |
+= | Add and reassign | x += 5 | x = x + 5 |
-= | Subtract and reassign | x -= 2 | x = x - 2 |
*= | Multiply and reassign | x *= 3 | x = x * 3 |
%= | Modulo and reassign | x %= 4 | x = x % 4 |
**= | Exponent and reassign | x **= 2 | x = x ** 2 |
` | =` | Conditional assignment |
Code Example (Parallel Assignment):
Multiple values can be assigned or swapped at once with Ruby’s capability for parallel assignment.
x, y, z = 1, 2, 3
puts "Before swap: x=#{x}, y=#{y}, z=#{z}"
x, y = y, x
puts "After swap: x=#{x}, y=#{y}, z=#{z}"
Output
Before swap: x=1, y=2, z=3
After swap: x=2, y=1, z=3
Comparison and Ordering Operators
These operators establish whether two values are equal or in relative order.
Operator | Operation | Description |
== | Equality | true if values are equal. |
!= | Not Equal | true if values are not equal. Defined automatically as the negation of == . |
< , <= , > , >= | Relational Ordering | Less than, less than or equal, greater than, greater than or equal. |
<=> | General Comparison | Returns $-1$ (left is less), $0$ (equal), or $+1$ (left is greater). |
=== | Case Equality | Used mainly in case statements; often overridden to check if an object is subsumed by a class or range. |
=~ | Pattern Match | Returns an index of match or nil . |
!~ | Pattern Mismatch | Negation of =~ . |
Code Example (Using the Spaceship Operator):
A class can automatically obtain definitions for the other relational operators (==, <, <=, etc.) by including the Comparable module if it defines the <=> operator.
# This line performs the comparison using the spaceship operator
result = 42 <=> 13
# This line prints the result to the console
puts "The result of 42 <=> 13 is: #{result}"
Output
The result of 42 <=> 13 is: 1
Logical Operators
For Boolean comparisons, logical operators are employed. Because they are more effective when employing short-circuit evaluation, the character versions (&&
, ||
) are typically advised over the word variants (and
, or
).
Operator | Operation | Precedence | Description |
&& | Boolean AND | High | Returns true if both operands are true values. |
` | ` | Boolean OR | |
and | Boolean AND | Low | Often used when low precedence relative to assignment is desired. |
or | Boolean OR | Low | Often used when low precedence relative to assignment is desired. |
Code Example (Boolean AND):
x = 0
y = 2
# This line checks if both conditions are true and then prints the result.
# The `&&` is the logical AND operator.
puts x == 0 && y > 1
Output
true
Bitwise and Shift Operators
For numbers, these operators (such as Fixnum and Bignum) operate at the bit level; nevertheless, they are sometimes overloaded to execute set operations or appends for collection types.
Operator | Operation | Application on Numbers | Application on Arrays |
& | Bitwise AND | Performs bitwise AND. | Performs set intersection. |
` | ` | Bitwise OR | Performs bitwise OR. |
^ | Bitwise XOR | Performs bitwise XOR. | – |
<< | Shift Left/Append | Bitwise shift-left. | Appends an element to a String, Array, or IO stream. |
>> | Shift Right | Bitwise shift-right. | – |
Code Example (Set Operations using Bitwise Operators on Arrays):
a = (63..66).to_a
b = (65..68).to_a
puts "Union: #{a | b}"
puts "Intersection: #{a & b}"
Output
Union: [63, 64, 65, 66, 67, 68]
Intersection: [65, 66]
Special Operators
Numerous distinct operators and pseudo-operators are defined by Ruby:
Bracket Operators ([]
and []=
): These are strong operators that are used to set and retrieve elements in collections. The syntax can be utilized on the left-hand side of an assignment expression by defining the corresponding []=
method.
Ternary Operator (?:
): As a condensed if/then/else statement, this is Ruby’s only ternary operator.
Range Operators (..
and ...
): Range objects are produced by these. The final value is inclusive in the two-dot form (..
) and exclusive in the three-dot form (…
). They function as a unique type of Boolean expression known as a flip-flop when incorporated into a conditional or loop.
Safe Navigation Operator (&.
): This operator, which was first introduced in Ruby 2.3.0, makes it easier to check for nil before accessing a property or invoking a function.
defined?
Operator: A unary operator that checks for the existence of its operand. It returns a string describing the operand’s type if it is defined, and nil otherwise. Although it is checked, the expression provided to defined? is not truly evaluated.
You can also read What Is Mean By Ranges In Ruby With Practical Code Examples