Close
Close

While loop in Ruby


I will start this chapter by asking you to take your friend's name as input. The solution is simple, you will use 'gets.chomp'. Now, if you have to ask the name of two friends, then you will use 'gets.chomp' two times. Now, suppose you have to take input of the name of 50 students.
No, no, no, using 'gets.chomp' for 50 times is not a good option. This kind of situations can be easily handled using loops. You will learn while loop in this chapter.

Before going further with loops, let's deal with something else first.

i = 1
puts i
i = i+1
puts i
i = i*5
puts i
i = i+10
puts i
i  = i*10
puts i
Output
1
2
10
20
200

The priority of '=' operator is lesser than that of '+' and '-'. So, it is also lesser than the priorities of *, / and **.

Initially, the value i is 1. Since the priority of + is higher than that of =, therefore in i = i+1, i+1 is 2 ( and it will be evaluated first ). So, this expression becomes equivalent to i = 2.
Now coming to i = i*5 - 5 gets multiplied to i ( 'i' is 2 ), so the expression becomes equivalent to 'i = 10'.
Then we add 10 to 'i' and assign the 'sum' to 'i', thus making the value of i equal to '20'. At last, we have, i = i*10. Considering * operator first, i*10 becomes 200 and the expression becomes i = 200.

Now you are ready to learn loops. A loop is same as its name. It repeats the codes inside its body to a fixed number of times ( not necessarily ). Let's see an example of while loop to print the multiplication table of 14 on screen:

i = 1
while i<=10
	puts i*14
	i=i+1
end
Output
14
28
42
56
70
84
98
112
126
140

So, the syntax of while loop is

while condition
  statement
  statement
  statement
  statement
  ....
end

A loop will run till its condition is getting sattisfied or the condition is true. The condition of the while loop in the above question is i<=10. This means that the codes inside the while loop will repeat if 'i' is less than or equal to 10.

Initially, 'i' is 1. The condition of while (i<=10) gets satisfied since the value of i is 1 (1 is less than 10). Thus the body of while gets executed and 'i*14' i.e., 1*14 (14) gets printed on the screen.
In the next line, i = i+1, increases the value of 'i' by 1, making its value equal to 2.
Again the condition of while loop gets satisfied, since the value of 'i' is 2 this time ( 2 is less than 10 ). Again its body gets executed and 'i*14' ( 2*14 ) i.e., 28 gets printed on the screen and 'i' fursther increased to 3.
Similarly, in 10th iteration, 'i' is 10 and 'i<=10' gets satisfied and 'i*14' ( 10*14 ) i.e., 140 gets printed on the screen and 'i' gets increased to 11.
Again checking the condition of while loop (i<=10) with 'i' equals 11, the condition is not satisfied and the loop stops.

So now you know that in the above example, the while loop will stop when i becomes greater than 10.

while loop in ruby
We use end in while loop also to end a while loop as used with if, else clause. end with while loop indicates the body of while loop ( where the while loop is terminating ).

Example including if and else


#initially more is 'True' to run the while loop for atleast once
more = true
while more==true
#Taking marks from user for marks
  puts "Enter you name"
  name = gets.chomp
  puts "Maths marks"
  maths_marks = gets.chomp.to_i
  puts "Science marks"
  science_marks = gets.chomp.to_i
  puts "English marks"
  english_marks = gets.chomp.to_i
  puts "Computer marks"
  comupter_marks = gets.chomp.to_i
  total = maths_marks+science_marks+english_marks+comupter_marks
  # using 400.0 to get faction value else if total will be less than 400(and mostly it will be) then it will be 0
  percentage = (total/400.0)*100
  puts "#{name} your total marks is #{total} and your percentage is #{percentage}"

  #User have to enter y if he want to run it again
  puts "Want to enter more y/n"
  a = gets.chomp
  if a!="y"
    #if user enters other than 'y' then making 'more' to 'False' to stop the loop. As condition in while will not be satisfied then
    more = false
  end
end
Output
Enter your name
sam
Maths marks
90
Science marks
92
English marks
85
Computer marks
94
sam , your total marks is 361 and your percentage is 90.25
Want to enter more y/n
y
Enter your name
rai
Maths marks
98
Science marks
82
English marks
89
Computer marks
90
rai , your total marks is 359 and your percentage is 89.75
Want to enter more y/n
n

The code inside the body of while is simple. It is taking marks as input and calculating the percentage and printing it on the screen.
After printing the total marks and percentage, again the user is asked to press 'y' or 'n' depending on whether the user wants to calculate more or not.
Now, if the user enters 'n', then the value of more will become false and then the condition of the loop ( more == true ) will not be satisfied and thus the loop will stop. But if the user enters 'y', then there will be no effect on the variable more, and the loop will be executed again.

The above 'while' will run till 'more' is true and it can change if we don't give 'y' to 'a'. (if a!= "y" -> more = false). And if we enter 'y', then whole loop will run again because 'more' is not changed and is still true.

Breaking of while loop


break is used to come out of the loop whenever we want. Whenever a loop encounters 'break', it just stops there and executes the rest of the code written after the loop. See this example to understand it more clearly.

#initially more is 'True' to run the while loop for atleast once
while true
#Taking marks from user for marks
  puts "Enter you name"
  name = gets.chomp
  puts "Maths marks"
  maths_marks = gets.chomp.to_i
  puts "Science marks"
  science_marks = gets.chomp.to_i
  puts "English marks"
  english_marks = gets.chomp.to_i
  puts "Computer marks"
  comupter_marks = gets.chomp.to_i
  total = maths_marks+science_marks+english_marks+comupter_marks
  # using 400.0 to get faction value else if total will be less than 400(and mostly it will be) then it will be 0
  percentage = (total/400.0)*100
  puts "#{name} your total marks is #{total} and your percentage is #{percentage}"

  #User have to enter y if he want to run it again or n to terminate
  puts "Want to enter more y/n"
  a = gets.chomp
  if a == "n"
    break
  end
end
Output
Enter your name
sam
Maths marks
90
Science marks
92
English marks
85
Computer marks
94
sam , your total marks is 361 and your percentage is 90.25
Want to enter more y/n
y
Enter your name
rai
Maths marks
98
Science marks
82
English marks
89
Computer marks
90
rai , your total marks is 359 and your percentage is 89.75
Want to enter more y/n
n

while true : The condition of the while loop is always true. This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it.
if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed. It is that simple. The remaining code is just the same as used in the previous example.

Infinite loop


As mentioned above, it is possible for a loop to run forever if its condition is always true. Let's see an example:
while true
  puts "I love Ruby"
end
Output
I love Ruby
I love Ruby
I love Ruby
I love Ruby
I love Ruby
I love Ruby
I love Ruby
I love Ruby
I love Ruby
I love Ruby
...
Press ctrl+c to stop this loop

Nesting of loop


Nesting means having one loop inside another. It means to have a loop inside the body of other loop. You have already studied about having one if under another, it is also similar. Let's see an example first.

a = 5
b = 1
while a>0
  while b<=5
    puts "*"*b
    b = b+1
    a = a-1
  end
end
Output
*
**
***
****
*****

Here, a is 5 and b is 1.
In the first iteration of the outer while loop, a is 1 and the inner while loop is inside the body of the outer while loop. So, the inner while loop will be executed and "*"*1 ( b is 1 ) i.e "*" will be printed and b will become 2 and a will become 4.
Now, the inner while loop will be executed again ( as b is 2 and b<=5 ), so "*"*2 i.e. "**" will be printed and the values of both b and a will become 3.
Again, only the inner loop will be executed and "*"*3 i.e. "***" will be printed. In the last iteration of inner while loop (with b equals 5), "*"*5 i.e. "*****" will be printed and b will become 6 and a will become 0.
Again the condition of inner while loop will be checked but it will be found false ( since the value of b is 6 ).
Now, the second iteration of the outer while will occur but since a is 0, so its condition is also false. So, it will also stop.

In short, there is nothing new in nesting of loops. Inner loop is like the other statements of a loop, after executing once, it will be completed first and then the rest of the statements of the outer loop will be executed.
Let's have a look on one more example on this:

a = 5
while a>0
  b = 1
  while b<=5
    puts "*"*b
    b = b+1
  end
  a = a-1
end
Output
*
**
***
****
*****
*
**
***
****
*****
*
**
***
****
*****
*
**
***
****
*****
*
**
***
****
*****

Try to understand this example yourself. Just go step by step with every while loop and you will understand this.

Making our own digital dice


Though this is not graphical but we will construct the working structure. You can learn to link graphics to this or any game after completing this course. For now, let's do this first.

puts "Give lower limit of dice"
a = gets.chomp.to_i
puts "Give upper limit of dice"
b = gets.chomp.to_i
puts "type q to Quit or any other key/enter to continue"
while true
  puts ">>> #{rand(a .. b)}"#rand is generating random number between a and b
  if gets.chomp == 'q' #if 'q' is entered then come out of loop
    break;
  end
end
Output
Give lower limit of dice
1
Give upper limit of dice
6
type q to Quit or any other key/enter to continue
>>> 1
>>> 2
>>> 2
>>> 5
>>> 4
>>> 3
>>> 6
>>> 3
q

rand function is used to generate a random numbers. rand(a .. b) will generate a random number between 'a' and 'b'. (a .. b) is the range function. You will study about this in Array chapter.

until


until is another loop provided by Ruby. It is exactly opposite of while loop. Thus, it repeats the codes inside its body till its condition is false. Let's see an example over this.

i = 0
until i>5
  puts i
  i = i+1
end
Output
0
1
2
3
4
5

When i becomes greater than 5, then the condition ( i>5 ) becomes true and the loop stops. Yes, as I mentioned earlier, it is opposite of while loop.

begin


The next thing is begin. First have a look at its syntax and an example.

begin
  statement
  statement
  statement
  statement
  ....
end while condition
begin
  statement
  statement
  statement
  statement
  ....
end until condition

The codes inside begin will be executed once ( first time ) without checking the condition of while/until. It is the same as 'do while' loop of languages like C, Java, etc. The codes inside begin will be executed once then, from second iteration it will start checking the condition of while or until. Let's see examples

i=0
begin
  puts i
  i=i+1
end while i<5
Output
0
1
2
3
4
i=0
begin
  puts i
  i=i+1
end until i<5
puts i
Output
0
1

Here, for the first time, the statements inside begin were executed, so 0 got printed on the screen and 'i' got increased to 1. After this, the condition of until was checked and it was found true ( until will run if condition is false ), so the loop stopped. After the loop, puts i printed the value of 'i' i.e. 1 ( value was increased to 1 in the first iteration of the loop ).

Don't practice until you get it right. Practice until you can't get it wrong.


Ask Yours
Post Yours
Doubt? Ask question