Ruby – The “and” and “or” operators

The “and” operatory can be used to string together several methods, here’s an example:

def hello
  puts "Hello"
  "returing: not-nil or false"
end

def aloha
  puts "aloha"
  # "returing: not-nil or false"
end

def bonjour
  puts "bonjour"
  "returing: not-nil or false"
end


hello and aloha and bonjour

This outputs:

PS C:\Temp\irb> ruby .\and.rb
Hello
aloha
bonjour
PS C:\Temp\irb>

If one of the method returns false or nil, then any methods following it will no longer run, here’s an example:

def hello
  puts "Hello"
  "returning: not-nil or false"
end

def aloha
  puts "aloha"
  # "returning: not-nil or false"      here we are now doing a nil output. 
end

def bonjour
  puts "bonjour"
  "returning: not-nil or false"
end


hello and aloha and bonjour

Now the output is:

PS C:\Temp\irb> ruby .\and.rb
Hello
aloha
PS C:\Temp\irb>

Notice this time that the bonjour method did not run this time.

Now here’s the “or” assignment in action:

def hello
  puts "Hello"
  "returning: not-nil or false"
end

def aloha
  return false      # Here we are terminating the method early by explictly using the "return" keyword. 
  puts "aloha"
end

def bonjour
  puts "bonjour"
  "returning: not-nil or false"
end

hello and aloha or bonjour

Here’s a few things to note:

  • && and || have much higher priority over “and” and “or”
  • && has higher priority over ||
  • “and” and “or” have equal priority over each other.