Ruby - why use a "do" when "while" can do the same

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 you need to be preferred over others? There is no reason for me to have until and while if they do the same. In my opinion, it is for this reason that other programming languages โ€‹โ€‹do not have both.

+5
source share
2 answers

This is about readability. The "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 
+10
source

What's better:

  • makeSoup while !ingredients.empty?
  • makeSoup until ingredients.empty?

while and until do the same, in some cases itโ€™s just โ€œbetter.โ€

+15
source

Source: https://habr.com/ru/post/1482269/


All Articles