Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is the body of a while statement a block?

As the title says, I’m getting confused about the difference between blocks and "normal" pieces of code that follow a statement.

I usually enclose the body of a while loop in Ruby with doend, e.g.

while true do
  # ...
end

But is it a block? If yes, why? If no, why is it declared as we declare blocks with methods?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

while is not a method but a keyword. This allows it to have its very own syntax (e.g. to make the do optional) and evaluation rules.

The body of a while loop is not a block. Blocks are sent to methods and while is not a method. You can’t pass a block argument to while (as in while(true, &block)) or refer to the body of a while loop or pass it around. It also doesn’t create a new variable scope like blocks do.

why is it declared as we declare blocks with methods?

I assume it’s out of convenience. Why would you use a different syntax if there’s already do and end? Re-using the same syntax for similar constructs (the body of a while loop, the body of a block, the body of a method etc.) makes it easier to read and write code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading