Home > Software design >  Is the body of a while statement a block?
Is the body of a while statement a block?

Time:07-22

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 do...end, 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?

CodePudding user response:

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.

  • Related