Ruby Questions and Answers Part-14

1. The given two expression means the same.
counter=counter+1 and counter++
a) True
b) False

Answer: a
Explanation: Both the expression increments the value by 1.

2. What is the output of the given code?
a = 22.5
while a >11.5
puts a
a-=3.5
end
a) 22.5 19.0 15.5 12.0
b) 22.5 11.5
c) 100..5
d) None of the mentioned

Answer: b
Explanation: The counter value will decrement by 3.5 till the counter value reaches 11.5.
Output:
22.5
19.0
15.5
12.0

3. What is the output of the given code?
a = 5
b=10
while a < 10 && b< 20
puts a+b
a+=2
b+=2
end
a) 10 20
b) 15 19 23
c) 15 16 17 18 19 20
d) None of the mentioned

Answer: b
Explanation: The counter value will increment by two till a< 10 and b< 20.
Output:
15
19
23

4. What is the output of the given code?
a = 5
b=10
while a < 10 && b< 20
puts a*b
a+=2
b+=2
end
a) 10 20
b) 15 19 23
c) 50 84 126
d) None of the mentioned

Answer: c
Explanation: The counter value will increment by two till a< 10 and b< 20 and multiply a and b.
Output:
50
84
126

5. What is the output of the given code?
a= 5
b=10
while a < 10 && b< 20
puts a-b
a+=2
b+=2
end
a) 10 20
b) 15 19 23
c) -5 -5 -5
d) None of the mentioned

Answer: c
Explanation: Even if both the values are incremented by two the difference remains the same.
Output:
-5
-5
-5

6. What is the output of the given code?
a = 5
b=10
while a < 10 || b< 20
puts a*b
a+=2
b+=2
end
a) 10 20
b) 50 84 126 176 234
c) -5 -5 -5
d) None of the mentioned

Answer: b
Explanation: The while will keep on executing even if only one condition is true.
Output:
50
84
126
176
234

7. What is the output of the given code?
a = 5
b=10
while (a < 10 || b< 20)&&true
puts a*b
a+=2
b+=2
end
a) 10 20
b) 50 84 126 176 234
c) -5 -5 -5
d) None of the mentioned

Answer: b
Explanation: The while will keep on executing when both the conditions are true.
Output:
50
84
126
176
234

8. While loop checks the condition and the loop keeps on running till the condition is true, it stops when the condition becomes false.
a) True
b) False

Answer: a
Explanation: While condition is true keep on looping.

9. What is the output of the given code?
counter = 1
while counter < 11
puts counter
counter = counter + 1
end
a) Prints the number from 1 to 10
b) Prints the number from 1 to 11
c) Prints the number from 2 to 10
d) Infinite loop

Answer: a
Explanation: Counter value is initialized to 1 and it keeps on looping till the counter is less than 11.
Output:
1
2
3
4
5
6
7
8
9
10

10. What is the output of the given code?
counter = true
while counter !=false
puts counter
end
a) True
b) False
c) Syntax error
d) Infinite loop

Answer: d
Explanation: Counter value is true in all cases hence true will be printed infinite times.
Output:
true
true
...Infinite loop