Start Coding

Topics

Ruby Operators

Ruby operators are special symbols that perform specific operations on one or more operands. They are essential for manipulating data and controlling program flow in Ruby.

Types of Ruby Operators

1. Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric values.

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus)
  • ** (Exponentiation)

Example:


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
    

2. Comparison Operators

Comparison operators are used to compare two values and return a boolean result.

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)
  • <=> (Spaceship operator)

Example:


x = 5
y = 10

puts x == y  # Output: false
puts x != y  # Output: true
puts x > y   # Output: false
puts x < y   # Output: true
puts x >= 5  # Output: true
puts y <= 9  # Output: false
puts x <=> y # Output: -1 (x is less than y)
    

3. Logical Operators

Logical operators are used to combine multiple conditions.

  • && (AND)
  • || (OR)
  • ! (NOT)

Example:


a = true
b = false

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

4. Assignment Operators

Assignment operators are used to assign values to variables.

  • = (Simple assignment)
  • += (Add and assign)
  • -= (Subtract and assign)
  • *= (Multiply and assign)
  • /= (Divide and assign)
  • %= (Modulus and assign)
  • **= (Exponentiate and assign)

Example:


x = 5
x += 3  # Equivalent to x = x + 3
puts x  # Output: 8

y = 10
y *= 2  # Equivalent to y = y * 2
puts y  # Output: 20
    

Operator Precedence

Ruby follows a specific order of precedence for operators. Understanding this order is crucial for writing correct expressions.

Precedence Operator
1 (Highest) **
2 !, ~, unary +
3 *, /, %
4 +, -
5 <<, >>
6 &
7 ^, |
8 <, <=, >, >=
9 ==, !=, ===, =~, !~
10 &&&
11 ||
12 (Lowest) .., ...

Best Practices

  • Use parentheses to clarify operator precedence in complex expressions.
  • Avoid using too many operators in a single expression to maintain readability.
  • Be cautious when using the == operator with floating-point numbers due to precision issues.
  • Utilize the Ruby Constants when working with fixed values to improve code maintainability.

Understanding Ruby operators is crucial for effective programming. They form the foundation for Ruby If-Else Statements, Ruby Loops, and other control structures. As you progress, you'll find operators essential in working with Ruby Arrays and Ruby Hashes.