Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Why use "until" when "while" can do the same [closed]

Tags:

ruby

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.

like image 987
a1204773 Avatar asked May 22 '13 21:05

a1204773


2 Answers

Which is better:

  1. makeSoup while !ingredients.empty?
  2. makeSoup until ingredients.empty?

while and until do the same thing, one is just "nicer" to read in some instances.

like image 175
wersimmon Avatar answered Oct 04 '22 21:10

wersimmon


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
like image 28
meagar Avatar answered Oct 04 '22 20:10

meagar