a = b || c
What this statement does is, it tells Ruby to 'assign the value of b
to a
, unless b
is falsy, if b
is falsy, assign the value of c
to a
. In case b
isn't falsy, the c
statement won't get executed.
A good example where you could use this is if you're getting a variable from somewhere and you're not sure if it's going to be nil or not, so you create a variable like c
as a second option.
If you have a method that takes in a hash as a parameter for example, and you want to return the value of the element from the hash that has the key 'b'
for example, but the hash parameter won't always have a 'b'
key, so you write something like this
def value_of_b(hash)
b_val = hash['b'] || 'unknown'
puts "The value of b is :#{b_val}"
end
h = {'a' => 1, 'b' => 2}
value_of_b(h)
#=>The value of b is :2
m = {'a' => 1}
value_of_b(m)
#=>The value of b is :unknown
Another example that comes to my mind is accessing an array element that doesn't exist
[1,2,3][3] || "default"
#=> "default"
Or having a default value for Rails params hash:
@name = params[:name] || "no name provided"