Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ruby eagerly evaluate expressions for 'while' but not 'if'

Tags:

ruby

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?

like image 686
jshen Avatar asked Apr 25 '26 07:04

jshen


1 Answers

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
like image 176
Shoe Avatar answered Apr 28 '26 05:04

Shoe