Ruby 中什么时候需要 do 关键字?
When is the do keyword required in Ruby?
例如,下面代码中 do
的存在与否是否会影响程序的行为?
while true do
puts "Hi"
break
end
while true
puts "Hi"
break
end
根据 The Ruby Programming Language 书第 5.2.1 节:
The do
keyword in a while
or until
loop is like the then
keyword in an
if
statement: it may be omitted altogether as long as a newline (or
semicolon) appears between the loop condition and the loop body.
所以,不,它不会改变行为,它只是可选语法。
让我们一探究竟!
为了快速回答,我们可以查看 Ruby 的文档并找到 http://www.ruby-doc.org/core-2.1.1/doc/syntax/control_expressions_rdoc.html#label-while+Loop,其中指出
The do keyword is optional.
好的,所以这两个示例是等效的,但它们是否相同?他们可能会做同样的事情,但也许有理由偏爱其中一个。我们可以查看这些示例生成的 AST,看看是否存在任何差异。
> gem install ruby_parser
> irb
> require 'ruby_parser'
=> true
> with_do = <<-END
while true do
puts "Hi"
break
end
END
=> "while true do\n puts \"Hi\"\n break\nend\n"
> without_do = <<-END
while true
puts "Hi"
break
end
END
=> "while true\n puts \"Hi\"\n break\nend\n"
> RubyParser.new.parse with_do
=> s(:while, s(:true), s(:block, s(:call, nil, :puts, s(:str, "Hi")), s(:break)), true)
> RubyParser.new.parse without_do
=> s(:while, s(:true), s(:block, s(:call, nil, :puts, s(:str, "Hi")), s(:break)), true)
没有。这两个示例执行完全相同的指令,因此我们可以选择我们认为更容易阅读的样式。一个普遍的偏好是尽可能省略 do
:https://github.com/bbatsov/ruby-style-guide#no-multiline-while-do
例如,下面代码中 do
的存在与否是否会影响程序的行为?
while true do
puts "Hi"
break
end
while true
puts "Hi"
break
end
根据 The Ruby Programming Language 书第 5.2.1 节:
The
do
keyword in awhile
oruntil
loop is like thethen
keyword in anif
statement: it may be omitted altogether as long as a newline (or semicolon) appears between the loop condition and the loop body.
所以,不,它不会改变行为,它只是可选语法。
让我们一探究竟!
为了快速回答,我们可以查看 Ruby 的文档并找到 http://www.ruby-doc.org/core-2.1.1/doc/syntax/control_expressions_rdoc.html#label-while+Loop,其中指出
The do keyword is optional.
好的,所以这两个示例是等效的,但它们是否相同?他们可能会做同样的事情,但也许有理由偏爱其中一个。我们可以查看这些示例生成的 AST,看看是否存在任何差异。
> gem install ruby_parser
> irb
> require 'ruby_parser'
=> true
> with_do = <<-END
while true do
puts "Hi"
break
end
END
=> "while true do\n puts \"Hi\"\n break\nend\n"
> without_do = <<-END
while true
puts "Hi"
break
end
END
=> "while true\n puts \"Hi\"\n break\nend\n"
> RubyParser.new.parse with_do
=> s(:while, s(:true), s(:block, s(:call, nil, :puts, s(:str, "Hi")), s(:break)), true)
> RubyParser.new.parse without_do
=> s(:while, s(:true), s(:block, s(:call, nil, :puts, s(:str, "Hi")), s(:break)), true)
没有。这两个示例执行完全相同的指令,因此我们可以选择我们认为更容易阅读的样式。一个普遍的偏好是尽可能省略 do
:https://github.com/bbatsov/ruby-style-guide#no-multiline-while-do