Ruby的一个班轮"并返回"

Yon*_*oni 1 ruby styles return

我最近发现了一个我不太了解的Ruby问题.那么,有人可以向我解释为什么Ruby中的这两个以下陈述不同 -

puts "foo" and return if true
Run Code Online (Sandbox Code Playgroud)

VS

if true
  puts "foo" 
  return 
end
Run Code Online (Sandbox Code Playgroud)

Bor*_*cky 5

要了解问题中的oneliner,您需要记住Ruby运算符及其优先级.或者更确切地说,Ruby语法.您需要以与Ruby解释器完全相同的方式查看语句.它必须成为你的第二天性.现在让我们来看看你的单行

puts "foo" and return if true
Run Code Online (Sandbox Code Playgroud)

让我们先把无关的问题分开.关键字return仅适用于方法或lambdas,并不是您的问题的主题.此外,尾随if true始终有效,因此似乎没有必要.要概括地讨论您的问题,让我们定义方法#bar和变量baz

def bar
  puts "bar"
end

baz = true
Run Code Online (Sandbox Code Playgroud)

让我们谈谈修改后的单线程

puts "foo" and bar if baz
Run Code Online (Sandbox Code Playgroud)

如果您已经记住了Ruby语法,那么您将能够像Ruby看到的那样完全填充该行:

( puts( "foo" ) and ( bar ) ) if ( baz )
Run Code Online (Sandbox Code Playgroud)

尾随if行为类似于优先级非常低的运营商.从头到尾的整行if只有在baz是真实的时才执行.因此,

puts "foo" and bar
Run Code Online (Sandbox Code Playgroud)

被执行.括号如下:

puts( "foo" ) and ( bar )
Run Code Online (Sandbox Code Playgroud)

您可以看到puts "foo"首先执行,foo在屏幕上打印并返回nil.由于nil是假的,操作员and只是返回它并且bar在其右侧永远不会被执行.

至于

if baz
  puts "foo"
  bar
end
Run Code Online (Sandbox Code Playgroud)

它相当于:

( puts( "foo" ); bar ) if ( baz )
Run Code Online (Sandbox Code Playgroud)

您可以看到差异:puts "foo"并且bar没有加入and,但是是独立的逻辑行.第一行的返回值被丢弃,不会影响第二行的执行.

最后,让我们来看看在更换发生什么and&&.因为&&运营商具有比andoneliner 高得多的优先级

puts "foo" && bar
Run Code Online (Sandbox Code Playgroud)

puts( "foo" && bar )
Run Code Online (Sandbox Code Playgroud)

换句话说,"foo" && bar首先计算值,然后作为参数传递给#puts方法.因为字符串"foo"被认为是真实的,所以执行继续进行bar,"bar"在屏幕上打印并返回nil.你可以自己尝试一下它的价值

"foo" && bar
Run Code Online (Sandbox Code Playgroud)

nil,"bar"在屏幕上印刷作为副作用.

puts( "foo" && bar )
Run Code Online (Sandbox Code Playgroud)

因此成为

puts( nil )
Run Code Online (Sandbox Code Playgroud)

这会导致在屏幕上打印空行.

士气是人们应该学习语法.Ruby设计师迈出了一大步,使代码可以像书本一样轻松阅读.