Tutorial: Operators in Ruby

Operators in Ruby are symbols or keywords used to perform operations on variables and values.

They are categorized based on their functionality, such as arithmetic, comparison, assignment, logical, and more.

What You’ll Learn

1. Introduction to Operators

Operators allow you to perform operations like addition, subtraction, comparison, and logical checks. Ruby supports operator overloading, allowing you to define the behavior of operators for custom objects.

2. Arithmetic Operators

Arithmetic operators perform basic mathematical operations.

Operator Description Example
+ Addition a + b
Subtraction a – b
* Multiplication a * b
/ Division a / b
% Modulus a % b
** Exponentiation a ** b

Examples

a = 10
b = 3

puts a + b  # Output: 13
puts a - b  # Output: 7
puts a * b  # Output: 30
puts a / b  # Output: 3
puts a % b  # Output: 1
puts a ** b # Output: 1000 (10^3)

3. Comparison Operators

Comparison operators compare two values and return a boolean (true or false).

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
<=> Combined comparison (spaceship) a <=> b

Examples

a = 10
b = 20

puts a == b   # Output: false
puts a != b   # Output: true
puts a > b    # Output: false
puts a < b    # Output: true
puts a >= 10  # Output: true
puts a <=> b  # Output: -1 (a is less than b)

4. Assignment Operators

Assignment operators assign values to variables and perform shorthand operations.

Operator Description Example
= Assign a = b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
**= Exponentiate and assign a **= b

Examples

a = 10
b = 5

a += b
puts a  # Output: 15

a *= 2
puts a  # Output: 30

a /= b
puts a  # Output: 6

5. Logical Operators

Logical operators combine or invert boolean expressions.

Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a

Examples

a = true
b = false

puts a && b  # Output: false
puts a || b  # Output: true
puts !a      # Output: false

6. Bitwise Operators

Bitwise operators perform operations on binary representations of integers.

Operator Description Example
& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise Complement ~a
<< Left shift a << 2
>> Right shift a >> 2

Examples

a = 6  # Binary: 110
b = 3  # Binary: 011

puts a & b  # Output: 2 (Binary: 010)
puts a | b  # Output: 7 (Binary: 111)
puts a ^ b  # Output: 5 (Binary: 101)
puts ~a     # Output: -7
puts a << 1 # Output: 12 (Binary: 1100)
puts a >> 1 # Output: 3 (Binary: 011)

7. Ternary Operators

A ternary operator is a compact form of an if-else statement.

Syntax

condition ? true_result : false_result

Example

age = 18
status = age >= 18 ? "Adult" : "Minor"
puts status  # Output: Adult

8. Range Operators

Range operators define sequences of numbers or characters.

Operator Description Example
.. Inclusive range (1..5)
Exclusive range (1…5)

Examples

inclusive_range = (1..5).to_a
puts inclusive_range.inspect  # Output: [1, 2, 3, 4, 5]

exclusive_range = (1...5).to_a
puts exclusive_range.inspect  # Output: [1, 2, 3, 4]

9. Practical Examples

9.1 Check for Even or Odd

number = 4
result = number.even? ? "Even" : "Odd"
puts result  # Output: Even

9.2 Find Maximum of Two Numbers

a, b = 10, 20
max = a > b ? a : b
puts "Maximum is #{max}"  # Output: Maximum is 20

9.3 Logical Operator in Conditions

age = 25
citizen = true

if age >= 18 && citizen
  puts "Eligible to vote"
else
  puts "Not eligible to vote"
end

9.4 Bitwise Masking

permissions = 0b1011  # Binary: 1011
read_mask = 0b0100    # Binary: 0100

can_read = (permissions & read_mask) != 0
puts "Read permission: #{can_read}"  # Output: Read permission: true

10. Summary

Key Takeaways

  • Ruby supports various operators for mathematical, logical, and bitwise operations.
  • Use assignment operators for concise and readable code.
  • Ternary operators provide a compact alternative to if-else statements.
  • Range operators simplify working with sequences.

Best Practices

  1. Use descriptive variable names to improve readability.
  2. Leverage range operators for looping or slicing arrays.
  3. Use parentheses for complex logical expressions to avoid ambiguity.

By mastering Ruby operators, you can write concise and efficient code for a wide range of tasks!

Related posts

Tutorial: Blocks in Ruby

Tutorial: Methods in Ruby

Tutorial: if…else Statements in Ruby