Ruby Questions and Answers Part-11

1. Which of the following is valid conditional statement in Ruby?
a) elseif
b) elsif
c) else if
d) elseiff

Answer: b
Explanation: We use elsif conditional statement in Ruby.

2. The elsif conditional statement is written with an expression.
a) True
b) False

Answer: a
Explanation: The syntax of elsif conditional statement is elsif with an expression.

3. The elsif statement can add many alternatives to if/else statements.
a) True
b) False

Answer: a
Explanation: We can add many conditions between if/else statements using elsif conditional statement.

4. What is the output of the given code?
counter=6
if counter<=5
puts (counter)
counter=counter+1
puts (counter)
elsif counter>5
puts (counter)
counter=2*counter
puts(counter)
else
puts(counter)
counter=counter-1
puts(counter)
end
a) 5
10
b) 6
12
c) Syntax error
d) None of the mentioned

Answer: b
Explanation: The counter value is 6 hence elsif part will get executed.
Output:
6
12

5. What is the output of the given code?
variable = false
if variable
print "false"
elsif !variable
print "true"
end
a) False
b) True
c) Syntax error
d) None of the mentioned

Answer: b
Explanation: !variable will evaluate to true so elsif block gets executed.
Output:
True

6. What is the output of the given code?
if !true
print "False"
elsif !true || true
print "True"
end
a) True
b) False
c) Syntax eroor
d) None of the mentioned

Answer: a
Explanation: !true || true evaluates to true, hence elsif block gets executed.
Output:
True

7. What is the output of the given code?
x=7
y=9
if x==y
print "equal"
elsif x>y
print "greater"
else
print "less"
end
a) equal
b) greater
c) less
d) none of the mentioned

Answer: c
Explanation: As x is less than y, hence else part will evaluate to true.
Output:
less

8. Boolean opeartors are also known as logical operators.
a) True
b) False

Answer: a
Explanation: Boolean operators result in boolean values like true or false

9. Which of the following is a valid boolean operator?
a) and(&&)
b) or(||)
c) not(!)
d) All of the mentioned

Answer: d
Explanation: We have three boolean operators which are and, or, not.

10. The boolean operator && only result in true when both the values are true?
a) True
b) False

Answer: a
Explanation: The && operator only results in true when both the values are true rest all cases it evaluates to false.