问题描述
在 http://guides.rubyonrails 浏览 Rails 指南时.org/layouts_and_rendering.html#avoiding-double-render-errors ,我写了一个测试程序来测试Ruby的&&返回
,我得到了这个奇怪的行为:
While going through the Rails guide at http://guides.rubyonrails.org/layouts_and_rendering.html#avoiding-double-render-errors ,I wrote a test program to test Ruby's && return
, and I got this strange behavior:
def test1
puts 'hello' && return
puts 'world'
end
def test2
puts 'hello' and return
puts 'world'
end
这是结果输出:
irb(main):028:0> test1
=> nil
irb(main):029:0> test2
hello
world
=> nil
造成这种差异的原因是什么?
What accounts for the difference?
推荐答案
查看and
和 &&
之间的区别.在示例中,您给出的方法 puts
在其参数周围没有括号的情况下被调用,并且优先级的差异改变了它的解析方式.
Check out the difference between and
and &&
. In the examples you give the method puts
is called without parens around it's arguments and the difference in precedence changes how it is parsed.
在测试 1 中 &&
比方法调用具有更高的优先级.所以实际发生的是puts('hello' && return)
.参数总是在调用它们的方法之前被评估——所以我们首先评估 'hello' &&返回
.由于 'hello'
是真实的,布尔值不会短路并且 return
被评估.当返回时,我们不做任何其他事情就退出该方法:因此没有记录任何内容并且第二行不会运行.
In test 1 &&
has higher precedence than the method call. So what's actually happening is puts('hello' && return)
. Arguments are always evaluated before the methods they're called with -- so we first evaluate 'hello' && return
. Since 'hello'
is truthy the boolean does not short circuit and return
is evaluated. When return we exit the method without doing anything else: so nothing is ever logged and the second line isn't run.
在测试 2 中 and
的优先级低于方法调用.所以发生的是puts('hello') 和return
.puts
方法记录传递给它的内容,然后返回 nil
.nil
是一个假值,所以 and
表达式短路,return
表达式永远不会被计算.我们只是移动到 puts 'world'
运行的第二行.
In test 2 and
has a lower precedence than the method call. So what happens is puts('hello') and return
. The puts
method logs what is passed to it and then returns nil
. nil
is a falsey value so the and
expression short circuits and the return
expression is never evaluated. We just move to the second line where puts 'world'
is run.
这篇关于红宝石:&&返回"vs “并返回"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!