When is the do keyword needed in Ruby?

For example, does the presence or absence of do in the following code really affect program behavior?

 while true do puts "Hi" break end while true puts "Hi" break end 
+7
ruby
source share
2 answers

According to the Ruby programming language in section 5.2.1:

The do keyword in a while or until while similar to the then keyword in if : it can be omitted altogether until a new line (or semicolon) appears between the loop condition and the body of the loop.

So no, this will not change the behavior, this is just an optional syntax.

+7
source share

Let's find out!

For a quick answer, we can look at the Ruby documentation and find http://www.ruby-doc.org/core-2.1.1/doc/syntax/control_expressions_rdoc.html#label-while+Loop , which states that

The do keyword is optional.

So these two examples are equivalent, but are they identical? They can do the same, but maybe there is a reason to support each other. We can look at the ASTs that generate these examples, and see if there is a difference.

 > 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) 

Nope. These two examples follow the same instructions so that we can choose the style that is easier for us to read. It is usually preferable to omit do : https://github.com/bbatsov/ruby-style-guide#no-multiline-while-do

+6
source share

All Articles