Ruby Questions and Answers - Unless Conditional Statement

1. What is the output of given code?
counter=1
if counter<=5
puts (counter)
counter=counter+1
else
puts(counter)
counter=counter-1
end
a) 1, 2
b) 1,2,3,4,5
c) 1 2 1
d) 1
2

  Discussion

Answer: d
Explanation: Value of counter is printed and then incremented.
Output:
1
2

2. What is the output of given code?
#counter=1
if counter<=5
puts (counter)
counter=counter+1
else
puts(counter)
counter=counter-1
end
a) Undefined local variable counter
b) 1,2,3,4,5
c) 1 2 1
d) 1
2

  Discussion

Answer: a
Explanation: Counter value must not be commented.
Output:
Undefined local variable counter

3. It is necessary that always if should come with else block?
a) True
b) False

  Discussion

Answer: b
Explanation: Not necessary, if can execute alone.

4. Syntax for unless conditional statement is
unless conditional [then]
code
else
code
end
a) True
b) False

  Discussion

Answer: a
Explanation: Executes code if condition is false. If the condition is true, code specified in the else clause is executed.

5. What is the output of the given code?
x=3
unless x>2
puts "x is less than 2"
else
puts "x is greater than 2"
end
a) x is greater than 2
b) x is less than 2
c) 3
d) None of the mentioned

  Discussion

Answer: a
Explanation: The unless conditional statement is true so the unless clause is not executed.

6. What is the output of the given code?
var = 1
print "1 -- Value is set\n" if var
print "2 -- Value is set\n" unless var
var = false
print "3 -- Value is set\n" unless var
a) 1–Value is set
b) 2–Value is set
c) 1–Value is set
2–Value is set
d) 1–Value is set
3–Value is set

  Discussion

Answer: d
Explanation: if condition is evaluated to true so it is executed and the second unless condition is evaluated to false so it is also executed.
Output:
1--Value is set
3--Value is set

7. What is the output of the given code?
hungry=false
unless hungry
print "Not hungry"
else
print "Hungry"
end
a) Not hungry
b) Hungry
c) Syntax error
d) None of the mentioned

  Discussion

Answer: a
Explanation: As hungry is initialized to false hence the unless condition is executed.

8. The following syntax is also used for unless conditional statement.
code unless conditional
a) True
b) False

  Discussion

Answer: a
Explanation: The unless condition must be false in order to execute the code.

9. What is the output of the given code?
counter=12
unless counter
print counter+1
else
print counter+2
end
a) 13
b) 14
c) 15
d) None of the mentioned

  Discussion

Answer: b
Explanation: Counter is assigned the value 1, so the unless conditional statement is true and hence it is not executed.

10. What is the output of the given code?
unless true && false
print "false"
else
print "ruby"
end
a) True
b) False
c) Nil
d) Syntax error

  Discussion

Answer: b
Explanation: true && false will evaluate to false so unless block will get executed.