Steven
Steven

Reputation: 2558

When is the do keyword required in Ruby?

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

while true do
    puts "Hi"
    break
end

while true
    puts "Hi"
    break
end

Upvotes: 10

Views: 929

Answers (2)

DiegoSalazar
DiegoSalazar

Reputation: 13531

According to The Ruby Programming Language book Section 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.

So, no, it won't change the behavior, it's just optional syntax.

Upvotes: 10

Jonah
Jonah

Reputation: 17958

Let's find out!

For a quick answer we can look at Ruby's 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.

Ok so these two examples are equivalent but are they identical? They might do the same thing but maybe there's a reason to favor one over the other. We can look at the AST these examples generate and see if there's any 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 execute the exact same instructions so we can pick whichever style we find easier to read. A common preference is to omit the do when possible: https://github.com/bbatsov/ruby-style-guide#no-multiline-while-do

Upvotes: 6

Related Questions