在Ruby中,布尔运算符(and
,or
,not
)可与sigil布尔运算符(&&
,||
,{ {1}})?我可以根据个人喜好在我的代码中使用任何一组运算符吗?
答案 0 :(得分:2)
在Ruby中,C风格的布尔运算符(!
,&&
,||
)不
可以与"英文单词"互换布尔运算符(not
,and
,or
)
因为它们相对于其他Ruby运算符具有不同的优先级。该
后者旨在用于程序流程控制。例如:
do_something_which_returns_true_on_success and
do_something_else_only_when_the_first_thing_succeeds
do_something_which_returns_false_on_failure or
do_something_else_if_the_first_thing_failed
1.9.3-p374 :023 > false and true ? "a" : "b"
=> false
1.9.3-p374 :024 > false && true ? "a" : "b"
=> "b"
1.9.3-p374 :097 > ! true ? 'a' : 'b'
=> "b"
1.9.3-p374 :098 > not true ? 'a' : 'b'
=> false
1.9.3-p374 :061 > x = 'a' and 'b'; x
=> "a"
1.9.3-p374 :062 > y = 'a' && 'b'; y
=> "b"
1.9.3-p374 :110 > z = ! true; z
=> false
1.9.3-p374 :111 > z = not true; z
SyntaxError: (irb):111: syntax error, unexpected keyword_true, expecting '('
1.9.3-p374 :092 > def troo; true; end
1.9.3-p374 :093 > def falce; false; end
1.9.3-p374 :094 > troo == ! falce
=> true
1.9.3-p374 :095 > troo == not falce
SyntaxError: (irb):95: syntax error, unexpected tIDENTIFIER, expecting '('
defined?
1.9.3-p374 :076 > undefined_variable
NameError: undefined local variable or method `undefined_variable' for main:Object
1.9.3-p374 :077 > defined? undefined_variable || 'a'
=> "expression"
1.9.3-p374 :078 > defined? undefined_variable or 'a'
=> "a"
1.9.3-p374 :079 > defined? undefined_variable && 'a'
=> "expression"
1.9.3-p374 :080 > defined? undefined_variable and 'a'
=> nil
1.9.3-p374 :083 > defined? 'a' && undefined_variable
=> "expression"
1.9.3-p374 :084 > defined? 'a' and undefined_variable
NameError: undefined local variable or method `undefined_variable' for main:Object
1.9.3-p374 :113 > defined? ! undefined_variable
=> nil
1.9.3-p374 :114 > defined? not undefined_variable
SyntaxError: (irb):114: syntax error, unexpected tIDENTIFIER, expecting '('
运算符and
和or
一词具有相同的优先级,因此
从左到右评估。相比之下,&&
的优先级高于||
。
1.9.3-p374 :150 > true || true && false
=> true
1.9.3-p374 :151 > true or true and false
=> false
1.9.3-p374 :153 > 1 || 2 && 3
=> 1
1.9.3-p374 :152 > 1 or 2 and 3
=> 3
上面的第四个案例(1 or 2 and 3
)可以这样解释:
1 or 2
。1
。1 and 3
。1
是真实的,因此流量控制会传递到and
的右侧。3
。代码行被认为是两种不同的表达方式。
相反,上面的第三种情况(1 || 2 && 3
)被认为是一个单独的表达,
和1 ||
处的短路,立即返回值1
。
1.9.3-p374 :163 > def meth1; puts "meth1 executed"; 1; end
1.9.3-p374 :164 > def meth2; puts "meth2 executed"; 2; end
1.9.3-p374 :165 > def meth3; puts "meth3 executed"; 3; end
1.9.3-p374 :166 > meth1 or meth2 and meth3
meth1 executed
meth3 executed
=> 3
1.9.3-p374 :167 > meth1 || meth2 && meth3
meth1 executed
=> 1