Why use Kernel#loop instead of Begin-end-while/until?

Asked

Viewed 53 times

2

I’m making a Ruby repetition structure using the following structure:

begin
  [código]
end <while/until> [condição]

But the Rubocop, which I use as a tool for linting, says I should use the Kernel#loop with break. Thus:

loop do
  [código]
  break <if/unless> [condição]
end

Why? In which cases should the begin-end-while/until? What advantages the Kernel#loop above brings in relation to the structure I used?

1 answer

2


I’m no expert on Ruby, but from what I’ve seen, it’s all about readability.

When you read the code and find a begin You’re thinking, start from what? There’s nothing clearly indicating there. Worse, it may be that some case the compiler itself may find that there is the beginning of something earlier and get very wrong.

Using the loop it becomes explicit that there begins a loop and easier to follow the flow and understand what is happening.

I find it interesting to raise the problems, but I do not like the suggestion offered, it even has the same semantics of the original code, so it induces error if the person does not understand what he is doing. But unfortunately the language does not offer a better option.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.