【问题标题】:Difference between or and || when setting variables或与||的区别设置变量时
【发布时间】:2010-12-10 04:52:12
【问题描述】:

我的印象是 ||or 是同义词。

使用or 设置变量不保存值;为什么?

>> test = nil or true
=> true
>> test
=> nil

>> test = false or true
=> true
>> test
=> false

||“按预期”工作

>> test = nil || true
=> true
>> test
=> true

【问题讨论】:

  • 这对我来说曾经是一个陷阱。

标签: ruby


【解决方案1】:

or优先级低于=

test = nil or true

一样
(test = nil) or true

这是true,同时将test设置为nil

|| 的优先级高于=

test = nil || true

一样
test = (nil || true)

这是true,同时将test设置为true

【讨论】:

  • ...这就是为什么我们不会写一段这样的代码,或者如果我们写了,我们总是用括号来说明发生了什么。
  • 谢谢,这很有道理。
  • 不仅||的优先级很高,or的优先级很低,而且andor的优先级相同,而@ 987654339@ 和&& 具有不同的优先级。通常,在条件表达式中,始终使用运算符形式,因为它们具有您实际期望它们具有的相对优先级。仅将andor 用于控制流,您实际上希望“内部”表达式绑定得更紧密。类似test = blah.get_records or puts 'No records found.'
【解决方案2】:

and&& 相同。我曾经被这个陷阱咬过,然后我意识到虽然and&& 更具可读性,但这并不意味着它总是更合适。

>> f = true && false
=> false
>> f
=> false
>> f = true and false
=> false
>> f
=> true
>> 

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多