This is the code using while
:
i = 0
num = 5
while i < num do
puts "Inside the loop! i = #{i}"
i += 1
end
This is the code using until
:
i = 0
num = 5
until i > num do
puts "Inside the loop! i = #{i}"
i += 1
end
Can someone give an example of when one should be preferred instead of the other? For me, there is no reason to have until
and while
if they do the same thing. In my opinion, this is the reason why other programming languages don't have both.
Which is better:
makeSoup while !ingredients.empty?
makeSoup until ingredients.empty?
while
and until
do the same thing, one is just "nicer" to read in some instances.
It's about readability. A "correct" example is completely subjective:
done = my_function until done
or
done = false
until done
# better than "while not done"? Who can say?
# do something that modifies the state of done
end
or
my_object.do_something until my_object.complete
# Or, if the method were otherwise named...
my_object.do_something while my_object.incomplete
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