Possible Duplicate:
Assigning a substitute value in case of nil
In Lua I use
x = value or "default_if_value_is_nil"
(as a shortcut for if value ~= nil then x = value end
)
Can I do something similar in Ruby?
Possible Duplicate:
Assigning a substitute value in case of nil
In Lua I use
x = value or "default_if_value_is_nil"
(as a shortcut for if value ~= nil then x = value end
)
Can I do something similar in Ruby?
x = value || "default_if_value_is_nil_or_false"
Note the "or false" here, though the same probably holds in Lua too.
You can actually do the same thing in ruby
x = nil_value || "default"
Note that this will also work for any other "falsey" value as well
x = false_value || "default"
x = value or "default_if_value_is_nil"
is a perfectly legal Ruby statement, but be aware that or
has one of the lowest priority in operators precedence. Also know that in a Ruby boolean operation everything is true except false and nil, thus this Ruby statement will also answer the default even if value is not nil but false.
puts '>>> assignment = has a higher priority than or <<<'
value = 'y'
x = value or "default_if_value_is_nil"
print 'value=', value.inspect, ', x=', x.inspect, "\n"
value = false
x = value or "default_if_value_is_nil"
print 'value=', value.inspect, ', x=', x.inspect, "\n"
value = nil
x = value or "default_if_value_is_nil"
print 'value=', value.inspect, ', x=', x.inspect, "\n"
puts '>>> put parenthesis around or expression to have a higher priority than = <<<'
value = 'y'
x = (value or "default_if_value_is_nil")
print 'value=', value.inspect, ', x=', x.inspect, "\n"
value = false
x = (value or "default_if_value_is_nil")
print 'value=', value.inspect, ', x=', x.inspect, "\n"
value = nil
x = (value or "default_if_value_is_nil")
print 'value=', value.inspect, ', x=', x.inspect, "\n"
puts '>>> || has a higher priority than = <<<'
value = 'y'
x = value || "default_if_value_is_nil"
print 'value=', value.inspect, ', x=', x.inspect, "\n"
value = false
x = value || "default_if_value_is_nil"
print 'value=', value.inspect, ', x=', x.inspect, "\n"
value = nil
x = value || "default_if_value_is_nil"
print 'value=', value.inspect, ', x=', x.inspect, "\n"
Output:
>>> assignment = has a higher priority than or <<<
value="y", x="y"
value=false, x=false
value=nil, x=nil
>>> put parenthesis around or expression to have a higher priority than = <<<
value="y", x="y"
value=false, x="default_if_value_is_nil"
value=nil, x="default_if_value_is_nil"
>>> || has a higher priority than = <<<
value="y", x="y"
value=false, x="default_if_value_is_nil"
value=nil, x="default_if_value_is_nil"