Ruby Questions and Answers Part-16

1. What is the output of the given code?
counter = 0
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: c
Explanation: Until the condition is false continue looping and here 10 will not be included because condition becomes true when counter is 10.
Output:
0
1
2
3
4
5
6
7
8
9

2. What is the output of the given code?
i = 3
while i > 0 do
puts i
i -= 1
end
j = 3
until j == 0 do
puts j
j -= 1
end
a) 1 2 3 1 2 3
b) 3 2 1 3 2 1
c) 0 1 2 3 4 5 6 7 8 9
d) None of the mentioned

Answer: c
Explanation: When it comes out of the while loop the until loop starts executing.
Output:
3
2
1
3
2
1

3. What is the output of the given code?
a="hungry"
until !a
puts "hungry"
a=!a
end
a) hungry
b) Nil
c) Error
d) None of the mentioned

Answer: a
Explanation: Until the condition is not met execute the loop.
Output:
hungry

4. What is the output of the given code?
m= 8
loop do
m += 2
puts m
break if m == 16
end
a) 10 12 14 16
b) Nil
c) Error
d) None of the mentioned

Answer: a
Explanation: Execute the loop till the condition is met.
Output:
10
12
14
16

5. What is the output of the given code?
m=0
loop do
print "ruby"
m+=1
break if m==5
end
a) rubyrubyrubyrubyrubyruby
b) rubyrubyrubyrubyruby
c) Error
d) None of the mentioned

Answer: b
Explanation: Execute the loop till m!=5 and then break when m=5.
Output:
rubyrubyrubyrubyruby

6. What is the output of the given code?
m=0
loop do
puts m*10
m+=1
break if m==5
end
a) 0 10 20 30 40
b) 10 20 30 40 50
c) Error
d) None of the mentioned

Answer: a
Explanation: Execute the loop till m!=5 and then print m*10.
Output:
0
10
20
30
40

7. What is the output of the given code?
m=0
loop do
puts 101
m+=1
break if m==5
end
a) 101 101 101 101 101
b) 10 20 30 40 50
c) Error
d) None of the mentioned

Answer: a
Explanation: Execute the loop till m!=5 and then print 101 five times.
Output:
101
101
101
101
101

8. What is the output of the given code?
m=5
loop do
m-=1
break if m==0
end
a) 1 2 3 4 5
b) 10 20 30 40 50
c) Error
d) Nil

Answer: d
Explanation: There is no print statement so the loop will execute 5 times and will not print anything.
Output:
nil

9. What is the output of the given code?
for num in 1...5
puts num
end
a) 1 2 3 4 5
b) 1 2 3 4
c) 2 3 4 5
d) None of the mentioned

Answer: b
Explanation: As the range i.e 1…10 is exclusive the loop will loop till 4 and then it will come out of the loop.
Output:
1
2
3
4

10. What does the 1…10 indicate?
a) Inclusive range
b) Exclusive range
c) Both inclusive and exclusive range
d) None of the mentioned

Answer: b
Explanation: 1…10 means start from one and go till 9 and don’t include 10.