Stats

95 Contributors: 5
Thursday, November 24, 2016
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Operators

Download ruby eBook

Remarks

Operators are methods

Most operators are actually just methods, so x + y is calling the + method of x with argument y, which would be written x.+(y). If you write a method of your own having semantic meaning of a given operator, you can implement your variant in the class.

As a silly example:

# A class that lets you operate on numbers by name.
class NamedInteger
  name_to_value = { 'one' => 1, 'two' => 2, ... }

  # define the plus method
  def + (left_addend, right_addend)
    name_to_value(left_addend) + name_to_value(right_addend)
  end

  ...
end

When to use && vs. and, || vs. or

Note that there are two ways to express booleans, either && or and, and || or or -- they are often interchangeable, but not always. We'll refer to these as "character" and "word" variants.

The character variants have higher precedence so reduce the need for parentheses in more complex statements helps avoid unexpected errors.

The word variants were originally intended as control flow operators rather than boolean operators. That is, they were designed to be used in chained method statements:

raise 'an error' and return

While they can be used as boolean operators, their lower precedence makes them unpredictable.

Secondly, many rubyists prefer the character variant when creating a boolean expression (one that evaluates to true or false) such as x.nil? || x.empty?. On the other hand, the word variants are preferred in cases where a series of methods are being evaluated, and one may fail. For example a common idiom using the word variant for methods that return nil on failure might look like:

def deliver_email
  # If the first fails, try the backup, and if that works, all good
  deliver_by_primary or deliver_by_backup and return
  # error handling code
end

Related Examples