Ruby Questions and Answers Part-15

1. What is the output of the given code?
i = 0
while i < 5
puts i
i=(i+1)**2
end
a) 1 2 3 4 5
b) 0 1 4
c) 0 1
d) 1 4

Answer: b
Explanation: (i+1)**2 means i+1 to the power of 2 and hence the loop continues till i< 5.
Output:
0
1
4

2. What is the output of the given code?
a=5
b=15
while a&&b
puts a+b
end
a) 5..15
b) 20
c) Infinite loop
d) 5 15

Answer: c
Explanation: a && b will always be true so the looping will never come to an end.
Output:
20
20
....infinite loop

3. What is the output of the given code?
a=5
b=15
while b>a
puts a*(b-a)
while a>b
a+=1
b-=1
end
end
a) 5..15
b) 50
c) Infinite loop
d) 5 50

Answer: c
Explanation: b>a will always be true so the looping will never come to an end and as a>b will always be false it will never enter the other while loop.
Output:
50
50
....infinite loop

4. What is the output of the given code?
i = 3
while i > 0 do
print i
i -= 1
end
a) 3
b) 321
c) Infinite loop
d) 3 2 1 0

Answer: b
Explanation: The do statement here indicates that till the while condition is true execute the instructions.
Output:
321

5. What is the output of the given code?
i = 50
while i > 25 do
print 50/i
i -= 1
end
a) 50..25
b) 50..1
c) Infinite loop
d) 1111111111111111111111111

Answer: d
Explanation: The do statement here indicates that till the while condition is true execute the instructions, so here it will print all the integer values of (50/i) which will always be one.
Output:
1111111111111111111111111

6. What is the output of the given code?
a = 5
b=10
while a < b do
puts a*b
a+=2
b-=2
end
a) 5 10
b) 50 56
c) Infinite loop
d) 5 6 7 8 9 10

Answer: b
Explanation: The do statement here indicates that till the while condition is true execute the instructions and will print a*b only till a
Output:
50
56

7. What is the output of the given code?
i = 50
j=55
while i > 25 && j>35 do
puts 50*j/i
i -= 1
j-=2
end
a) 25 35
b) 50 55
c) Infinite loop
d) 55 54 53 52 51 50 48 47 46 45

Answer: b
Explanation: It will print integer value of (50*j)/i
Output:
55
54
53
52
51
50
48
47
46
45

8. What is the output of the given code?
i = 50
j=55
while i > 25 && i*j< 100 do
puts (50*j)/i
i -= 1
j-=2
end
a) 25 35
b) No output
c) Infinite loop
d) 55 54 53 52 51 50 48 47 46 45

Answer: b
Explanation: The while condition is never true so no output.
Output:
nil

9. The complement of while loop is until loop.
a) True
b) False

Answer: a
Explanation: The until loop is sort of like backward while.

10. What is the output of the given code?
counter = 1
until counter > 10
puts counter
counter+=1
end
a) 1 2 3 4 5 6 7 8 9 10
b) 11 12 13 14 … infinite loop
c) 0 1 2 3 4 5 6 7 8 9
d) None of the mentioned

Answer: a
Explanation: Until the condition is false continue looping.
Output:
1
2
3
4
5
6
7
8
9
10