Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 134 ยท Getting Started

Operators

Learn Ruby operators - arithmetic, comparison, the spaceship, logical && and and, assignment and ||=, safe navigation, ranges, bitwise ops and precedence rules.

An operator is a symbol such as +, == or && that combines values. In most languages operators are built-in syntax. In Ruby, almost every operator is a method call in disguise: 3 + 4 is 3.+(4), and a == b is a.==(b). This is why you can define + for your own classes (Operator Overloading) and why "ab" * 3 and [1, 2] + [3] work. A few operators (&&, ||, !, defined? and assignment) are real syntax and cannot be redefined.

This lesson covers the operators you use every day, a few that surprise newcomers (integer division, and versus &&, ||=), and how Ruby decides which operator goes first.

Arithmetic

Ruby Arithmetic operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Integer division floors. -7 / 2 is -4, not -3, and % follows the same rule so that a == (a / b) * b + a % b always holds. If you want C-style truncation use remainder or Integer#truncate on a float division. Dividing by zero raises an error for integers but not for floats:

Ruby Division by zero (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first three lines print Infinity, -Infinity and true; the last stops the program with main.rb:4:in 'Integer#/': divided by 0 (ZeroDivisionError). The numbers lesson (Numbers) covers floats, rationals and rounding.

Comparison

Ruby Comparison operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

== asks whether two values are equal. <=>, the spaceship, returns -1, 0 or 1 (or nil if the values cannot be compared) and powers sorting. === is case equality, used by case/when and grep: a range, class or regex uses it to answer "does this value belong to me?". More on equality in Equality and Identity.

Comparing incompatible types with < or > raises an error:

Ruby Comparing unlike things (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After true, the program stops with main.rb:2:in 'Integer#<': comparison of Integer with String failed (ArgumentError).

Logical operators and truthiness

Only two values are falsy in Ruby: false and nil. Everything else, including 0, "" and [], is truthy. The logical operators therefore return one of their operands, not necessarily true or false.

Ruby Short-circuit logic returns operands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

&& and || are short-circuit: the right side runs only if needed. That is what makes user && user.name safe and name || "Anonymous" a default. ! and !! negate and normalize. &, | and ^ on booleans do not short-circuit; on integers they are bitwise operators (see below).

and, or and not are different

Ruby also has low-precedence word versions. They exist for flow control, not for conditions:

Ruby and versus &&

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

b = false or true assigns false to b, because assignment binds tighter than or. That is the classic trap. The words and/or read well for control flow (do_work or raise "failed") but for ordinary conditions use &&, || and !. Most style guides ban and/or in conditions entirely.

Assignment operators

Ruby Assignment shortcuts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

a ||= b means "if a is nil or false, set it to b". It is Ruby's idiom for defaults and for memoizing a value once. Beware: x ||= true cannot flip a false flag back to false, because false is replaced. Ruby has no ++ or --; write count += 1. Parallel assignment evaluates all right-hand values before assigning, which is why swapping works.

Strings, arrays and ranges have operators too

Ruby Operators on collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

.. includes the end of a range, ... excludes it. << appends and returns the receiver, so appends chain. [] is also an operator (a method called []), and it is what makes hash[:a] work.

Bitwise operators

Ruby Bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You need these for flags, masks and low-level work. They are rare in everyday application code.

The safe navigation operator

&. calls a method only when the receiver is not nil; otherwise the whole call evaluates to nil.

Ruby Safe navigation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

It saves you a verbose user && user.name. Do not scatter &. everywhere: a nil that should never happen deserves an error. See Ternary, Safe Navigation and Short-Circuit for the idioms.

Other operators worth knowing

  • ? : is the conditional (ternary) operator: age >= 18 ? "adult" : "minor".
  • defined?(x) returns a description ("local-variable", "method", ...) or nil.
  • :: accesses constants and modules (Math::PI).
  • .() is shorthand for .call, used on lambdas.
  • ** before a hash and * before an array splat arguments (Method Arguments).
  • ->(x) { } creates a lambda.
Ruby defined? and ternary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Precedence

When an expression has several operators, Ruby follows a precedence table. From highest to lowest:

TEXT
!  ~  unary+
**
unary-
*  /  %
+  -
<<  >>
&
|  ^
>  >=  <  <=
<=>  ==  ===  !=  =~  !~
&&
||
..  ...
? :
modifier-rescue
=  +=  -=  etc.
defined?
not
or  and
modifier-if  modifier-unless  modifier-while  modifier-until

Memorizing the table is unnecessary. Use parentheses whenever the order is not obvious to a reader, and remember the three surprises: ** is right-associative and beats unary minus, assignment is below || and && but above or and and, and a method call without parentheses grabs everything to its right.

Ruby Parentheses clarify (and one trap)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A subtle warning: puts (1 + 2) * 3 has a space before the parenthesis, so Ruby reads it as puts((1 + 2) * 3) and prints 9, and the space makes it easy to misread. Write puts((1 + 2) * 3) or assign to a variable first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is -7 / 2 in Ruby?

    Integer division floors toward negative infinity, so -3.5 becomes -4. Use -7.fdiv(2) for -3.5 or remainder for C-style behavior.
  2. 2. After b = false or true, what is b?

    or has lower precedence than =, so this parses as (b = false) or true. Use || in conditions and expressions.
  3. 3. What does name ||= "guest" do when name is already "Ann"?

    ||= assigns only when the variable is nil or false. A string, even an empty one, is truthy, so nothing happens.
  4. 4. Which value is falsy in Ruby?

    Only nil and false are falsy. Zero, empty strings and empty arrays are all truthy.
  5. 5. What does 1 <=> "a" return?

    The spaceship operator returns nil when two objects cannot be compared. The comparison operators < and > raise ArgumentError instead.

Summary

  • Most Ruby operators are methods (a + b is a.+(b)); &&, ||, !, defined? and assignment are syntax.
  • Integer / and % floor; use floats or fdiv for fractions, and ** binds tighter than unary minus.
  • == compares values, eql? also class, equal? identity, <=> ordering and === case membership.
  • Only nil and false are falsy; && and || short-circuit and return an operand.
  • and/or/not have very low precedence: use them for flow control only.
  • ||=, &&= and parallel assignment make defaults and swaps compact.
  • &. guards against nil. When in doubt about order, add parentheses.

Next: if, elsif, else and unless