Ruby Questions and Answers Part-17

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

Answer: b
Explanation: This is a nested loop.
Output:
1
1
2
2
2
4
3
3
6

2. What is the output of the given code?
m= 0
loop do
m += 1
print m
break if m == 10
end
a) 12345678910
b) 1 2 3 4
c) 2 3 4 5
d) None of the mentioned

Answer: a
Explanation: Loop till the condition is met and break when the condition is not satisfied.
Output:
12345678910

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

Answer: c
Explanation: Loop till the condition is met and break when the condition is not satisfied.
Output:
1
4
9
16
25

4. What is the output of the given code?
for num in 1..3
puts num*num
m= 0
loop do
m += 1
puts m
break if m == 3
end
end
a) 12345678910
b) 1 1 2 3 4 1 2 3 9 1 2 3
c) 1 4 9 16 25
d) None of the mentioned

Answer: c
Explanation: Loop till the condition is met and break when the condition is not satisfied.
Output:
1
1
2
3
4
1
2
3
9
1
2
3

5. What is the output of the given code?
loop do
m += 1
puts m
break if m == 3
end
a) Garbage values
b) 1 1 2 3 4 1 2 3 9 1 2 3
c) 1 4 9 16 25
d) None of the mentioned

Answer: a
Explanation: Loop till the condition is met and break when the condition is not satisfied.
Output:
Garbage values

6. What is the output of the given code?
i=1
for i in 5..10
puts i^2
end
a) 7 4 5 10 11 8
b) 25 36 49 64 81 100
c) 1 4 9 16 25
d) None of the mentioned

Answer: b
Explanation: Initialize the value of i and then print i**2.
Output:
25
36
49
64
81
100

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

Answer: a
Explanation: 1..10 means start from one and go till 9 and even include 10.

8. What is the output of the given code?
i=5
j=10
for i in 5..10 && j in 5..10
puts i**j
end
a) Syntax error
b) 25 36 49 64 81 100
c) 1 4 9 16 25
d) None of the mentioned

Answer: a
Explanation: Initialize the value of i and j and then when condition is true print i**j.

9. Arrays can be used to store multiple values in one single variable.
a) True
b) False

Answer: a
Explanation: We can store multiple value in one single variable known as arrays.

10. What will be output of the given code?
my_array = [1, 2, 3, 4]
print my_array
a) [1, 2, 3, 4].
b) 1234
c) Error
d) None of the mentioned

Answer: a
Explanation: A variable my_array is declared and [1, 2, 3, 4] is stored in that variable.
Output:
[1, 2, 3, 4]