Control flow with logic statements

suggest change

While it might seem counterintuitive, you can use logical operators to determine whether or not a statement is run. For instance:

File.exist?(filename) or STDERR.puts "#{filename} does not exist!"

This checks whether the file exists and prints the error message only if it does not. or is lazy: it stops as soon as the result is known. If the first term is true, the result is true and the second term is not evaluated. If the first term is false, the second term is evaluated.

A common use is to set a default value:

glass = glass or 'full' # Optimist!

That sets glass to 'full' when the current value is nil or false. glass must already exist; an unset local variable raises NameError. More concisely, use the symbolic form of or:

glass ||= 'empty' # Pessimist.

It’s also possible to run the second statement only if the first one is false:

File.exist?(filename) and puts "#{filename} found!"

Again, and is lazy so it will only execute the second statement if necessary to arrive at a value.

The or operator has lower precedence than and. Similarly, || has lower precedence than &&. The symbol forms have higher precedence than the word forms. This is handy to know when you want to mix this technique with assignment:

a = 1 and b = 2
#=> a==1
#=> b==2
a = 1 && b = 2; puts a, b
#=> a==2
#=> b==2

Note that the Ruby Style Guide recommends:

The and and or keywords are banned. The minimal added readability is just not worth the high probability of introducing subtle bugs. For boolean expressions, always use && and || instead. For flow control, use if and unless; && and || are also acceptable but less clear.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents