Skip to content

Ruby Operators

Ruby provides a rich set of operators, many of which are syntactic sugar for method calls. For instance, a + b is typically interpreted as a.+(b), where the + method of the object a is called with b as an argument. This allows classes to define custom behavior for standard operators (operator overloading).

For most binary arithmetic and bitwise operators (e.g., +, -, *, /, %, **, &, |, ^, <<, >>), there is a corresponding abbreviated assignment operator (e.g., +=, -=, etc.).

Assume variable a holds 10 and variable b holds 20:

OperatorDescriptionExample
+Addition: Adds values on either side.a + b will give 30
-Subtraction: Subtracts the right-hand operand from the left-hand operand.a - b will give -10
*Multiplication: Multiplies values on either side.a * b will give 200
/Division: Divides the left-hand operand by the right-hand operand. If both are integers, performs integer division (truncates result).b / a will give 2. 10 / 3 gives 3. 10.0 / 3 gives 3.333…
%Modulus: Divides the left-hand operand by the right-hand operand and returns the remainder.b % a will give 0. 10 % 3 gives 1.
**Exponentiation: Raises the left-hand operand to the power of the right-hand operand.a**2 (a to the power of 2) will give 100

These operators compare two values and return true or false. Assume a = 10 and b = 20:

OperatorDescriptionExample
==Equality: Checks if the values of two operands are equal. May perform type conversion (e.g., 10 == 10.0 is true).(a == b) is false.
!=Inequality: Checks if the values of two operands are not equal.(a != b) is true.
>Greater than: Checks if the value of the left operand is greater than the right operand.(a > b) is false.
<Less than: Checks if the value of the left operand is less than the right operand.(a < b) is true.
>=Greater than or equal to.(a >= b) is false.
<=Less than or equal to.(a <= b) is true.
<=>Combined comparison (spaceship) operator: Returns 0 if operands are equal, 1 if the first is greater, and -1 if the first is less. Essential for sorting.(a <=> b) returns -1. (a <=> 10) returns 0.
===Case equality (triple equals): Used implicitly in case statements. Its behavior varies by class. For example, (1..10) === 5 is true (checks if 5 is in the range). String === "hello" is true (checks if “hello” is an instance of String).(1...10) === 5 returns true.
.eql?Type and value equality: Returns true if the receiver and argument have both the same type and equal values.1 == 1.0 returns true, but 1.eql?(1.0) is false.
.equal?Object identity: Returns true if the receiver and argument refer to the exact same object in memory.If x = "hi" and y = "hi", then x == y is true, but x.equal?(y) is usually false (they are different string objects). If z = x, then x.equal?(z) is true.

Assume a = 10 and b = 20:

OperatorDescriptionExample
=Simple assignment: Assigns value from the right side to the left side operand.c = a + b assigns the value of a + b to c.
+=Add AND assignment: Adds the right operand to the left operand and assigns the result to the left operand.c += a is equivalent to c = c + a.
-=Subtract AND assignment.c -= a is equivalent to c = c - a.
*=Multiply AND assignment.c *= a is equivalent to c = c * a.
/=Divide AND assignment.c /= a is equivalent to c = c / a.
%=Modulus AND assignment.c %= a is equivalent to c = c % a.
**=Exponent AND assignment.c **= a is equivalent to c = c ** a.

Ruby supports assigning multiple variables in a single statement. This is useful for initializing several variables at once or for swapping values.

a = 10
b = 20
c = 30

Can be written as:

a, b, c = 10, 20, 30

To swap the values of two variables:

x = 5
y = 10
x, y = y, x # Now x is 10, y is 5

Bitwise operators work on the binary representation of integers.

Assume a = 60 (binary 00111100) and b = 13 (binary 00001101):

a = 00111100
b = 00001101
-----------------
a & b = 00001100 (12)
a | b = 00111101 (61)
a ^ b = 00110001 (49)
~a = 11000011 (complement, interpretation depends on signedness and system)
OperatorDescriptionExample (a=60, b=13)
&Bitwise AND: Copies a bit to the result if it exists in both operands.(a & b) will give 12 (binary 00001100).
|Bitwise OR: Copies a bit if it exists in either operand.(a | b) will give 61 (binary 00111101).
^Bitwise XOR: Copies the bit if it is set in one operand but not both.(a ^ b) will give 49 (binary 00110001).
~Bitwise Complement (NOT): Unary operator, flips all bits.(~a) will give -61 (in 2’s complement for a typical signed integer representation).
<<Bitwise Left Shift: Shifts bits of the left operand to the left by the number of positions specified by the right operand. Fills with zeros.a << 2 will give 240 (binary 11110000).
>>Bitwise Right Shift: Shifts bits of the left operand to the right. Behavior for negative numbers (arithmetic vs. logical shift) can depend on implementation, but for positive numbers, it fills with zeros.a >> 2 will give 15 (binary 00001111).

Logical operators are used to combine conditional statements. In Ruby, false and nil are considered falsy, while all other values (including 0, [], "") are truthy.

Assume a = true, b = false, x = 10 (truthy), y = nil (falsy):

OperatorDescriptionPrecedenceExample
&&Logical AND: Returns true if both operands are truthy. Evaluates lazily (short-circuits).Higher(a && x) is true. (b && x) is false.
||Logical OR: Returns true if at least one operand is truthy. Evaluates lazily (short-circuits).Higher(a || b) is true. (b || y) is false.
!Logical NOT (Unary): Reverses the logical state of its operand.Highest!a is false. !b is true.
andLogical AND: Similar to && but with lower precedence.Lower(x and a) is true. (y and a) is nil (returns the falsy value).
orLogical OR: Similar to || but with lower precedence.Lower(x or b) is 10 (returns the first truthy value). (y or b) is false.
notLogical NOT: Similar to ! but with lower precedence.Lowernot a is false. not b is true.

Important Note on Precedence: && and || have higher precedence than and and or. This difference is crucial. For example, result = x || y && z is different from result = x or y and z. It’s generally recommended to use && and || for boolean logic and and/or for control flow (e.g., do_something or raise "Error"). Parentheses can clarify intent.

The ternary operator provides a concise way to write simple if-else statements. Syntax: condition ? expression_if_true : expression_if_false.

OperatorDescriptionExample
? :Conditional Expressionage = 20; status = (age >= 18 ? "Adult" : "Minor") (status will be “Adult”)

Range operators create Range objects representing a sequence of values.

OperatorDescriptionExample
..Inclusive range: Creates a range from the start point to the end point, including the end point.1..5 creates a range representing 1, 2, 3, 4, 5.
...Exclusive range: Creates a range from the start point up to, but not including, the end point.1...5 creates a range representing 1, 2, 3, 4.

defined? is a special operator (looks like a method call) that checks if a given expression (variable, method, etc.) is defined. It returns a string describing the type of the expression if defined, or nil if not defined. It’s useful for introspection and conditional code execution.

Examples:

foo = 42
defined? foo # => "local-variable"
defined? $global # => "global-variable" (if $global is defined, else nil)
defined? bar # => nil (if bar is not defined as a variable or method)
defined? puts # => "method" (if puts is a defined method in scope)
defined? Math::PI # => "constant" (if Math::PI is defined)
defined? MyClass # => "constant" (if MyClass is a defined class)
defined? yield # => "yield" (if a block is passed to the current method), else nil
defined? super # => "super" (if the current method can call super), else nil

Ruby Dot (.) and Double Colon (::) Operators

Section titled “Ruby Dot (.) and Double Colon (::) Operators”
  • Dot operator (.): Used to call methods on an object. Example: my_string.length, my_array.sort.
  • Double Colon operator (::): A scope resolution operator. Used to access constants (including classes and modules) defined within a class or module. Example: Math::PI, MyModule::MyClass. It can also be used to call class methods if the class itself is treated as a constant in some contexts, but ClassName.class_method is more common.

Example of :: for constants:

module MyModule
MY_CONSTANT = "Hello from MyModule"
class Helper
HELPER_CONSTANT = "Helper here!"
end
end
puts MyModule::MY_CONSTANT # => Hello from MyModule
puts MyModule::Helper::HELPER_CONSTANT # => Helper here!

The following table lists operators from highest precedence (evaluated first) to lowest. Operators on the same line generally have similar precedence and are evaluated based on associativity (usually left-to-right, except for exponentiation and assignment).

Operator(s)DescriptionAssociativity
::Constant resolutionLeft
[] []=Element reference, element setLeft
**ExponentiationRight
! ~ + - (unary)Logical NOT, Bitwise NOT, Unary Plus, Unary MinusRight
* / %Multiplication, Division, ModulusLeft
+ - (binary)Addition, SubtractionLeft
>> <<Bitwise Right Shift, Bitwise Left ShiftLeft
&Bitwise ANDLeft
^ |Bitwise XOR, Bitwise ORLeft
<= < > >=Comparison operatorsLeft (Chaining allowed, e.g. a < b < c)
<=> == === != =~ !~Equality, Case Equality, Pattern Match operatorsLeft (Non-associative for some like == in complex chains without parens)
&&Logical AND (high precedence)Left
||Logical OR (high precedence)Left
.. ...Range creationNon-associative
? :Ternary conditionalRight
= %= /= -= += |= &= >>= <<= *= &&= ||= **=Assignment operatorsRight
defined?Check if definedN/A
notLogical NOT (low precedence)Right
or andLogical OR and AND (low precedence)Left

Note: Many operators listed are methods and can be overridden. Using parentheses () is always a good practice to ensure clarity and enforce the desired order of operations when in doubt.