在Lua中我使用
x = value or "default_if_value_is_nil"
(为if value ~= nil then x = value end
快捷方式)
我能做类似的事情呃Ruby?
在Lua中我使用
x = value or "default_if_value_is_nil"
(为if value ~= nil then x = value end
快捷方式)
我能做类似的事情呃Ruby?
x = value || "default_if_value_is_nil_or_false"
请注意这里的“或false”,虽然在Lua中也可能也是这样。
实际上,你可以做同样的事情在红宝石
x = nil_value || "default"
注意,这也适用于任何其他的“falsey”值以及工作
x = false_value || "default"
x = value or "default_if_value_is_nil"
是一个完全合法的Ruby声明,但请注意,or
在运算符优先级中具有最低优先级之一。也知道在一个Ruby布尔操作中,除了false和nil之外,一切都是真实的,因此,即使值不是零而是假,这个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"
哇,这很简单。 ||之间有什么区别?然后在Ruby中呢? –
优先。 '或'具有非常低的优先级,所以'a = b或c'被解释为'(a = b)或c'。 – Thomas
@Bożena优先级不同,请参阅[在Ruby中使用'和'&'或](http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ )和[Ruby中'或'和'||'之间的区别](http://stackoverflow.com/questions/2083112/difference-between-or-and-in-ruby)。 –