Ruby Questions and Answers Part-13

1. What will be the output of the given code?
boolean_1 = !true
puts boolean_1
boolean_2 = !true && !true
puts boolean_2
a) True True
b) False False
c) True False
d) None of the mentioned

Answer: c
Explanation: !true = false and !true and !true will evaluate to false.
Output:
False
False

2. What will be the output of the given code?
boolean_2 = !true && (!true || 100 != 5**2)
puts boolean_2
a) True
b) False
c) Error
d) None of the mentioned

Answer: b
Explanation: 100 != 5**2 is true and true || false is true but true and !true is false hence the overall expression will evaluate to false.
Output:
False

3. Which of the following is a valid assignment operator?
a) +=
b) -=
c) *=
d) All of the mentioned

Answer: d
Explanation: Assignment operators are +=, -=, *=, /=, **=.

4. What does the **= assignment operator do?
a) Multiplies the value twice
b) It is used as exponent like 2**3=8
c) It is the multiplication operator.
d) None of the mentioned

Answer: b
Explanation: a**=2 means a to the power of two.

5. What is the output of the given code?
counter = 2
while counter < 68
puts counter
counter**=2
end
a) 2 4 16 64
b) 2 4 16
c) 2 4 16 256
d) None of the mentioned

Answer: b
Explanation: The counter will increment by the power of two.
Output:
2
4
16

6. What is the output of the given code?
counter = 1
while counter < 11
puts counter
counter+=1
end
a) 1 2 3 4 5
b) 1…10
c) 1..10
d) None of the mentioned

Answer: c
Explanation: 1..10 inclusive 10 also. The counter will increment by one.
Output:
1
2
3
4
5
6
7
8
9
10

7. Ruby does not support ++ operator, it only supports += operator.
a) True
b) False

Answer: a
Explanation: Ruby does not support ++ or — operator. It only supports += or -= operator.

8. What is the output of the given code?
counter = 100
while counter > 0
puts counter
counter/=5
end
a) 100 20 4
b) 100 20 5
c) 100..5
d) None of the mentioned

Answer: a
Explanation: First counter will be 100 then after division it will become 20 then again it will become 4 and then it will come out of the loop.
Output:
100
20
4

9. What is the output of the given code?
counter = 100
while counter > 0
puts counter
counter-=25
end
a) 100 75 50 25
b) 100 25 5
c) 100..5
d) None of the mentioned

Answer: a
Explanation: The counter value will decrement by 25.
Output:
100
75
50
25

10. What is the output of the given code?
counter = -50
while counter < 0
puts counter
counter+=10
end
a) 100 75 50 25
b) -50 -40 -30 -20 -10
c) 100..5
d) None of the mentioned

Answer: b
Explanation: The counter value will decrement by 10 till the counter value reaches zero.
Output:
-50
-40
-30
-20
-10