Boolean Or Operator
Two pipes (||
) makes for the Boolean Or operator in Ruby. This is an important operator for writing conditional logic expressions in our code. We can think of it as a way to fallback to the remaining part of the expression if the first part isn't truthy.
It is useful for providing a default value to a variable. For instance, if params[:name]
is not provided, we can fallback to a default string value.
> who = params[:name] || "World"
=> "World"
> puts "Hello, #{who}!"
Hello, World!
=> nil
The or
operator is similar to the ||
operator in use, but has a different precedence. It is idiomatic in Ruby to use ||
unless you have a specific reason to use or
.