Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the do keyword required in Ruby?

Tags:

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
like image 298
Steven Avatar asked Jan 12 '15 19:01

Steven


People also ask

What is do end Ruby?

There are two ways of defining a block in Ruby: The first is using the do.. end keyword, the other is using a pair of curly braces. Do.. end block is mainly used when defining a block of code that spans multiple lines, while curly braces {} are used when defining a block of code that spans a single line.

Why do we use begin and end in Ruby?

Ruby's BEGIN and END blocks (in uppercase) are reserved keywords in Ruby and are pretty straightforward to use. They enable you to specify blocks of code that you want your program to run at the beginning and end of its execution, regardless of their position in the source file.

What is reserved words in Ruby?

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error. Example: # Ruby program to illustrate Keywords.

What is identifiers in Ruby?

Ruby Identifiers Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby. Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ).


1 Answers

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.

like image 101
DiegoSalazar Avatar answered Oct 09 '22 08:10

DiegoSalazar