我知道有在another answer所示優先級的差別:爲什麼可以寫或不寫||?
p foo = false || true
# => true
p foo = false or true
# => false
但似乎有更多的東西那是or
和||
不同。
例如:
p foo = 42 or raise "Something went wrong with foo"
# => 42
p foo = nil or raise "Something went wrong with foo"
# => Something went wrong with foo (RuntimeError)
p foo = 42 || raise "Something went wrong with foo"
# => syntax error, unexpected tOP_ASGN, expecting end-of-input
我期待得到:
p foo = 42 or raise "Something went wrong with foo"
# => 42
p foo = nil or raise "Something went wrong with foo"
# => Something went wrong with foo (RuntimeError)
p foo = 42 || raise "Something went wrong with foo"
# => Something went wrong with foo (RuntimeError)
但它是一個語法錯誤。那麼發生了什麼?
許多Rubiests,包括我自己在內,*不要*使用'和'或'或'。用'&&'和'||'堅持會簡化你的生活,而不會限制你的選擇。 –