Prelude
这样做的目的是测试所有可能的场景。
Note当说“操作员X
比方法调用具有更高的优先级”意思是在论证中。又名:
invocation foo X bar
与(调用对象)相反
X invocation
就第二种情况而言,方法调用始终具有更高的优先级。
简短回答
它不适合:
- 它导致
SyntaxError
在某些情况下
- 它的优先级高于
rescue
,但低于赋值
Summary
-
not
无论括号如何,都不能在方法调用后使用
- 使用括号 (
()
) 方法调用有时会导致SyntaxError
。这些案例是:and
, or
, if
, unless
, until
, while
and rescue
- 如果括号不会导致错误,它们不会以任何方式改变优先级
- 所有运营商,除了
and
, or
, 后缀if
, unless
, until
, while
, rescue
比方法调用具有更高的优先级
让我们尝试一下:
class Noone < BasicObject
undef_method :!
def initialize(order)
@order = order
end
def method_missing(name, *args)
@order << name
self
end
end
第一个一元:
# + and - will become binary
unary_operators = %i(! ~ not defined?)
puts 'No brackets'
unary_operators.each do |operator|
puts operator
order = []
foo = Noone.new order
bar = Noone.new order
begin
eval("foo.meta #{operator} bar")
rescue SyntaxError => e
puts e
end
p order
puts '-----------'
end
puts 'Brackets'
unary_operators.each do |operator|
puts operator
order = []
foo = Noone.new order
bar = Noone.new order
begin
eval("foo.meta(#{operator} bar)")
rescue SyntaxError => e
puts e
end
p order
puts '-----------'
end
获得的积分:
-
not
方法调用之后是SyntaxError
- 无论括号如何,所有一元运算符都比方法调用具有更高的优先级
现在二进制:
binary_operators = %i(
**
* / %
+ -
<< >>
&
| ^
> >= < <=
<=> == === =~
.. ...
or and
)
puts 'No brackets'
binary_operators.each do |operator|
order = []
foo = Noone.new order
bar = Noone.new order
baz = Noone.new order
begin
eval("foo.meta bar #{operator} baz")
rescue SyntaxError => e
puts e
end
p order
end
puts 'Brackets'
binary_operators.each do |operator|
order = []
foo = Noone.new order
bar = Noone.new order
baz = Noone.new order
begin
eval("foo.meta( bar #{operator} baz)")
rescue SyntaxError => e
puts e
end
p order
end
获得的积分:
- 方法调用周围的括号
and
or or
is a SyntaxError
- 我们必须测试
and
and or
进一步没有括号
-
..
and ...
call <=>
。我们必须进一步测试这一点
- 我们无法通过这种方式测试其他一些二元运算符,即
&&
, ||
, ==
, !=
, 修饰符rescue
, if
, unless
, until
, while
- 除上述之外,无论括号如何,运算符都具有更高的优先级
def yes
puts 'yes'
true
end
def no
puts 'no'
false
end
def anything(arg)
puts 'Anything'
arg
end
anything yes and no
anything no or yes
anything yes && no
anything no || yes
anything(yes && no)
anything(no || yes)
anything yes == no
anything(yes == no)
anything yes != no
anything(yes != no)
获得的积分:
-
and
and or
不带括号的优先级较低
-
&&
, ||
, ==
and !=
无论括号如何,都具有更高的优先级
def five(*args)
p args
5
end
five 2..7
five(2..7)
five 2...7
five(2...7)
获得的积分:
-
..
and ...
无论括号如何,都具有更高的优先级
anything yes if no
anything(yes if no)
anything no unless yes
anything(no unless yes)
anything no until yes
anything(no until yes)
anything yes while no
anything(yes while no)
获得的积分:
- 括号里有
if
, unless
, until
, while
导致SyntaxError
- 以上所有内容的优先级都低于不带括号的方法调用
def error
puts 'Error'
raise
end
anything error rescue yes
anything(error rescue yes)
获得的积分:
- 周围的括号
rescue
导致SyntaxError
-
rescue
如果不存在括号,则优先级较低
Ternary:
anything yes ? no : 42
anything(yes ? no : 42)
获得的积分:
作业(留到最后,因为它发生了变化yes
and no
):
anything yes = no
anything(no = five(42))
获得的积分:
注意+=
之类的只是快捷方式+
and =
所以他们表现出相同的行为。