Operators in Ruby
Ruby provides the familiar categories of operators found in most languages—arithmetic, comparison, logical, assignment—but with a crucial twist: most operators in Ruby are actually syntactic sugar for method calls defined on objects. This means 1 + 2 is equivalent to 1.+(2), and it also means you can override operator behavior for your own classes by defining methods named +, ==, <=>, and so on. Understanding this early demystifies a lot of what initially looks like special syntax.
Cricket analogy: Watching a bowler's action, it looks like one fluid motion, but it's really a sequence of defined mechanics; likewise 1 + 2 looks like special syntax but is really 1.+(2), a method call you can override for a Score class.
Arithmetic, Comparison, and Logical Operators
Ruby supports the standard arithmetic operators + - * / % ** (the last being exponentiation), along with comparison operators == != > < >= <= and the combined comparison operator <=> (the 'spaceship operator'), which returns -1, 0, or 1 depending on relative ordering, or nil if the values are not comparable. For logical operations, Ruby has two sets: the symbolic && || ! and the keyword-based and or not. They behave similarly but have different precedence—the keyword forms bind more loosely, which can cause surprising results if mixed carelessly with assignment.
Cricket analogy: The <=> spaceship operator ranking values -1, 0, or 1 is like comparing two batting averages to decide who tops the table, while Ruby's keyword and/or binding more loosely than &&/|| is like a scorer misreading a rule if two conventions are mixed carelessly.
puts 1 + 2 # => 3, equivalent to 1.+(2)
puts 10 % 3 # => 1 (modulo)
puts 2 ** 5 # => 32 (exponentiation)
puts 5 <=> 3 # => 1 (spaceship: left is greater)
puts 3 <=> 3 # => 0 (equal)
puts 1 <=> 5 # => -1 (left is less)
# Symbolic vs keyword logical operators have different precedence
result = false || true # result => true
result = false or true # result => false! (assignment binds tighter than 'or')Assignment, Ranges, and Safe Navigation
Beyond simple assignment (=), Ruby supports compound assignment operators like +=, -=, ||= (assign only if the variable is currently nil or false — commonly used for memoization or default values), and &&=. Ruby also has range operators: .. creates an inclusive range and ... creates an exclusive range (excluding the final value). The safe navigation operator &., introduced in Ruby 2.3, calls a method only if the receiver is not nil, returning nil instead of raising a NoMethodError, which is invaluable for chaining calls on potentially nil values.
Cricket analogy: ||= is like only updating the scoreboard's 'best partnership' record if it's currently blank, and Ruby's &. safe navigation is like a commentator checking if a batter exists before reading their strike rate, avoiding a broadcast crash.
count ||= 0 # sets count to 0 only if it was nil/false, else keeps existing value
count += 1 # shorthand for count = count + 1
(1..5).to_a # => [1, 2, 3, 4, 5] (inclusive range)
(1...5).to_a # => [1, 2, 3, 4] (exclusive range)
user = nil
user&.profile&.name # => nil, no error, instead of NoMethodError on nilBecause operators like +, ==, and <=> are just methods, you can redefine them on your own classes (operator overloading) to make custom objects behave naturally with arithmetic and comparisons—covered in depth in the operator overloading topic.
Mixing &&/|| with and/or is a classic Ruby pitfall: because and/or have lower precedence than =, a line like result = compute_value or default_value assigns only the result of compute_value to result, not the full expression — almost never what the author intended.
- Most Ruby operators (+, -, ==, <=>, etc.) are actually method calls on objects, enabling operator overloading.
- The spaceship operator
<=>returns -1, 0, 1, or nil, and underpins sortable and Comparable objects. - Symbolic (&&, ||) and keyword (and, or) logical operators differ in precedence, not just style.
||=assigns a value only if the variable is currently nil or false, commonly used for memoization...creates an inclusive range and...creates an exclusive range.- The safe navigation operator
&.avoids NoMethodError by short-circuiting to nil on a nil receiver.
Practice what you learned
1. What does the expression `1 + 2` actually represent under the hood in Ruby?
2. What values can the spaceship operator `<=>` return?
3. What does `count ||= 0` do if `count` is already set to 5?
4. What is the difference between the range `(1..5)` and `(1...5)`?
5. What does the safe navigation operator `&.` do when the receiver is nil?
Was this page helpful?
You May Also Like
Variables and Data Types
Learn how Ruby variables work, its dynamic typing model, and the core built-in data types: integers, floats, strings, symbols, booleans, and nil.
Conditional Statements in Ruby
How to control program flow in Ruby with if/elsif/else, unless, ternary expressions, and modifier conditionals, plus Ruby's truthiness rules.
Operator Overloading
Learn how Ruby implements operators as ordinary methods, letting you define custom `+`, `==`, `<<`, and other operators on your own classes for expressive, idiomatic APIs.
Comparable and Enumerable Modules
See how Ruby's Comparable and Enumerable modules let a class gain dozens of methods for free by implementing just one core method each: `<=>` or `each`.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics