Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the while and until loops in ruby?

In Ruby there are to loops that appear to do the exact same thing as each other, the while and until loops.

What would be a situation to use one over the other and why does Ruby have two loops that seem to do the same thing?

The while loops syntax is as follows:

while conditional [do]
   code
end

And the until syntax:

until conditional [do]
   code
end

So to make this as clear as possible:

$i = 0
$num = 5

while $i < $num  do
   puts("Inside the loop i = #$i" )
   $i +=1
end

And

$i = 0
$num = 5

until $i < $num  do
   puts("Inside the loop i = #$i" )
   $i +=1;
end

Will produce both the same out put of:

Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
like image 904
kCC Avatar asked Aug 19 '15 00:08

kCC


1 Answers

ruby allows multiple ways of doing exactly the same thing, so that the code can read naturally depending on which sounds better for you and the code you are writing. Sometimes a conditional works better in the positive eg something_is_happening? vs the negative something_is_done

and while works while something positive is continuing to be positive, whereas until continues the loop until something negative occurs.

eg

while 'yes' == keep_going do
   keep_going = get_answer
end

vs

until 'stop' == answer do
   answer = get_answer
end

Also i note that you haven't actually tried running your two loops in irb...I know this because the output of the second one is definitely not the same as the first.

2.1.2 :008 > $i = 0
 => 0 
2.1.2 :009 > $num = 5
 => 5 
2.1.2 :010 > 
2.1.2 :011 >   until $i < $num  do
2.1.2 :012 >        puts("Inside the loop i = #$i" )
2.1.2 :013?>      $i +=1;
2.1.2 :014 >     end
 => nil 

This is because when ruby interprets "is $i < $num yet" it evaluates to true and then stops immediately.

like image 181
Taryn East Avatar answered Sep 28 '22 17:09

Taryn East