价值或“默认”

时间:2012-12-30 21:48:26

标签: ruby

  

可能重复:
  Assigning a substitute value in case of nil

在Lua我使用

x = value or "default_if_value_is_nil"

(作为if value ~= nil then x = value end的快捷方式)

我可以在Ruby中做类似的事情吗?

3 个答案:

答案 0 :(得分:4)

x = value || "default_if_value_is_nil_or_false"

请注意这里的“或假”,尽管Lua也可以这样做。

答案 1 :(得分:2)

你可以在ruby中实际做同样的事情

x = nil_value || "default"

请注意,这也适用于任何其他“假”值

x = false_value || "default"

答案 2 :(得分:2)

x = value or "default_if_value_is_nil"

是完全合法的Ruby语句,但要注意or具有运算符优先级中最低优先级之一。还要知道在Ruby布尔操作中除了false和nil之外一切都是正确的,因此即使value不是nil而且是false,这个Ruby语句也会回答默认值。

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"

输出:

>>> 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"