Logical Operators

Ruby gives you three operators for combining true/false values:

&&

and — true if both sides are true

||

or — true if at least one side is true

!

not — flips true into false and vice versa

$ irb
>> true && true
=> true
>> true && false
=> false
>> true || false
=> true
>> !true
=> false
>> exit

Because only false and nil are falsy (see true, false, and nil), these operators work with any Ruby value, not just booleans.

A Handy Idiom: Default Values with ||

|| does not strictly return true or false — it returns the first value that is not false or nil. That makes it a clean way to supply a default:

$ irb
>> name = nil
=> nil
>> display_name = name || 'Anonymous'
=> "Anonymous"
>> name = 'Stefan'
=> "Stefan"
>> display_name = name || 'Anonymous'
=> "Stefan"
>> exit

You will see this pattern constantly in Ruby and Rails code.

Ruby also has and, or and not as word forms. They look friendlier, but have a much lower precedence than &&, || and !, which makes them surprising in practice. The community convention is to stick with the symbol forms.