Operators
suggest changeRemarks
Operators are methods
Most operators are methods. x + y calls the + method of x with argument y, which you can also write as x.+(y). To give an operator your own meaning, define that method on the class.
As a silly example:
# A class that lets you operate on numbers by name.
class NamedInteger
VALUES = { 'one' => 1, 'two' => 2 }.freeze
def initialize(name)
@value = VALUES.fetch(name)
end
# define the plus method
def +(other)
@value + other.to_i
end
def to_i
@value
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 they need fewer parentheses in complex statements and are less likely to surprise you.
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:
save and return
While they can be used as boolean operators, their lower precedence makes them unpredictable.
Many people use the character form for a boolean expression, such as x.nil? || x.empty?. The word forms show up when a series of methods is run for control flow and one of them may fail. and and or have the same precedence and associate to the left. A common idiom, for methods that return nil or false on failure:
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