Notice how the while version evaluates the expression, but the if version does not.
begin
puts 'hi'
1
end while false
# => hi
# => nil
begin
puts 'hi'
1
end if false
# => nil
But if we use an expression without begin ... end it will not eagerly evaluate it.
puts 'hi' while false
# => nil
Is there a reason for this seeming discrepancy?
The begin-end-while (also called do-while in other languages) is supposed to run the block of code at least once (therefore leading to the printing of "hi") and repeat it as long as the condition is met.
while X
Y
end
is not equal to:
begin
Y
end while X
The first will never execute the Y block of code if the condition X is never met. The second will, firstly, evaluate the block of code Y once and then will check if the condition X is met: if it is, then it runs the block Y again and again until the condition X evaluates to false.
A normal begin-end-if block, instead, is just considered like any other if block: it will be ignored (or just not executed) if the conditional expression evaluates to false.
if X
Y
end
is, instead, equal to:
begin
Y
end if X
which is the same as:
Y if X
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With