Operators
Ruby has all the operators you'd expect, plus a few unique ones. Comparison operators: ==, !=, <, >, <=, >=. The spaceship operator <=> returns -1, 0, or 1 โ great for sorting. Logical operators: &&, ||, !. The range operator .. creates ranges. Ternary: condition ? true : false. Compound assignment with +=. Case equality ===. Fun fact: operators in Ruby are actually method calls under the hood.
# Comparison operators
puts 5 == 5 # => true
puts 5 != 3 # => true
puts 5 < 10 # => true
puts 5 > 10 # => false
puts 5 <= 5 # => true
puts 5 >= 10 # => false
# Spaceship operator โ returns -1, 0, or 1
puts 5 <=> 3 # => 1
puts 5 <=> 5 # => 0
puts 5 <=> 10 # => -1
# Logical operators
puts true && false # => false
puts true || false # => true
puts !true # => false
# Range operator
(1..5).each { |i| print "#{i} " } # => 1 2 3 4 5
(1...5).each { |i| print "#{i} " } # => 1 2 3 4 (exclusive)
# Ternary operator
age = 20
status = age >= 18 ? "adult" : "minor"
puts status # => "adult"
# Compound assignment
x = 10
x += 5 # x = x + 5 = 15
x -= 3 # x = x - 3 = 12
x *= 2 # x = x * 2 = 24
# Case equality
puts (1..10) === 5 # => true (5 is in the range)
puts /^h/ === "hello" # => true (matches regex)
Try it Yourself ->