TExcelTAD
Home › Ruby › Ruby Operators

Ruby Operators

Operators are symbols that combine or compare values: +, ==, && and so on. A surprising fact about Ruby is that most operators are methods. 3 + 4 is really 3.+(4). That is why your own classes can define what + or == means for them.

ruby · try it yourself
p 3 + 4
p 3.+(4)
p "ab".*(3)
7
7
"ababab"

Arithmetic operators

Operator Name Example Result
+ addition 5 + 2 7
- subtraction 5 - 2 3
* multiplication 5 * 2 10
/ division 5 / 2 2
% modulo 5 % 2 1
** exponent 5 ** 2 25

They also work on other types: "a" + "b", [1] + [2], "-" * 5, [1, 2, 3] - [2].

Assignment operators

=, plus the combined forms +=, -=, *=, /=, %=, **=, ||= and &&=:

ruby · try it yourself
total = 100
total -= 15
total *= 2
total %= 60
p total

cache = nil
cache ||= "computed"
p cache

name = "zoe"
name &&= name.capitalize   # only runs if name is truthy
p name
50
"computed"
"Zoe"

Comparison operators

Operator Meaning
== equal value
!= not equal
> < >= <= greater / less
<=> "spaceship": -1, 0 or 1 (or nil if not comparable)
=== case equality (used by case/when)
eql? equal value and same type
equal? same object
ruby · try it yourself
p 5 == 5.0
p 5.eql?(5.0)
p 3 <=> 7
p "b" <=> "a"
p 4 <=> "x"
p (1..10) === 5
p Integer === 5
p /ab/ === "cab"
true
false
-1
1
nil
true
true
true

=== reads as "does the left side describe the right side?": a range contains the number, a class matches its instances, a regex matches the string. case/when uses exactly this operator.

Logical operators

Operator Meaning Example
&& and age >= 18 && member
|| or admin || owner
! not !done

Both && and || short-circuit and return one of their operands, not just true/false:

ruby · try it yourself
p true && "yes"
p nil && "never evaluated"
p nil || "fallback"
p false || nil
p "first" || "second"
p !nil
"yes"
nil
"fallback"
nil
"first"
true

Note: Ruby also has the words and, or and not, but with very low precedence. x = true and false assigns true to x! Use &&, || and ! in expressions; reserve and/or for control flow like save or raise "failed".

Safe navigation &.

&. calls a method only if the receiver is not nil; otherwise it returns nil instead of raising an error:

ruby · try it yourself
user = {profile: nil}
p user[:profile]&.fetch(:city)
p "text"&.upcase
city = user[:profile]&.fetch(:city) || "unknown"
p city
nil
"TEXT"
"unknown"

Other useful operators

Operator Example Meaning
? : n > 0 ? "pos" : "neg" ternary (inline if/else)
.. / ... 1..5, 1...5 inclusive / exclusive range
<< arr << 4, str << "x" append (or bit shift for integers)
defined? defined?(foo) is this name defined?
& | ^ ~ 6 & 3 bitwise operators on integers
=~ "cat" =~ /a/ regex match position

Precedence

From high to low, the most common ones are: ! → ** → unary - → * / % → + - → << >> → & → | ^ → > >= < <= → <=> == === != =~ → && → || → .. ... → ? : → assignment → not → and or.

ruby · try it yourself
p 2 + 3 * 4
p (2 + 3) * 4
p -2 ** 2
p 10 - 2 - 3
14
20
-4
5

-2 ** 2 is -(2 ** 2) because ** binds tighter than unary minus. When in doubt, add parentheses.

Test yourself

What does nil || "default" return?

  1. nil
  2. true
  3. "default"
  4. false

What does 5 <=> 9 return?

  1. true
  2. -1
  3. 1
  4. 4

What does user&.name do when user is nil?

  1. Raises NoMethodError
  2. Returns nil
  3. Returns an empty string
  4. Creates a user