Ruby Questions and Answers Part-6

1. The following syntax is correct for if conditional statement.
if condition
code
end
a) True
b) False

Answer: a
Explanation: The condition is true then only the code inside will execute.

2. If expression.
The expression can be of which type?
a) True
b) Any number
c) Any string
d) All of the mentioned

Answer: d
Explanation: The condition must be true then if statement works.

3. What error does the if condition gives if not terminated with end statement?
a) Syntax error
b) Unexpected end
c) Expecting keyword end
d) All of the mentioned

Answer: d
Explanation: We will get all the three errors.

4. What is the output of the following?
if 1<2
print "one is less than two"
end
a) One is less than two
b) Syntax error
c) 1<2
d) None of the mentioned

Answer: a
Explanation: The given condition is true so print statement gets executed.
Output: One is less than two

5. What is the output of the code?
if 11<2
print "Eleven is less than two"
end
print "11 is greater"
a) 11 is greater
b) Eleven is less than two
c) Eleven is less than two 11 is greater
d) None of the mentioned

Answer: a
Explanation: The condition given in the if statement is not true hence it comes out of the if block.
Output: 11 is greater

6. What is the output of the given code?
if 11>2
puts "Eleven is greater than two"
end
print "You'r right"
a) Eleven is greater than two
b) You’r right
c) Eleven is greater than two
You’r right
d) None of the mentioned

Answer: c
Explanation: If condition is true then code is executed and then it comes out and then execute the remaining code.
Output:
Eleven is greater than two
You'r right

7. What is the output of the given code?
if 79>78
puts "True".upcase
if 9>8
puts "True".reverse
if 7==7
puts "equal".downcase
end
end
end
a) True
b) True eurt
c) TRUE
eurT
equal
d) equal

Answer: c
Explanation: String methods are used and every condition is true, hence every if block is executed.
Output:
TRUE
eurT
equal

8. What is the output of the given code?
if 79>78
puts "True".upcase
if 9>8
puts "True".Upcase
if 7==7
puts "equal".downcase
end
end
end
a) True
b) Error
c) True,error
d) TRUE
Undefined method `Upcase’ for String

Answer: d
Explanation: Method should always be in smallcase.
Output:
TRUE
Undefined method `Upcase' for String

9. If statement inside if statement is called Nested if statements.
a) True
b) False

Answer: a
Explanation: Nested if means statement inside statement.

10. What is the output of the given code?
x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
a) x is greater than 2
b) x is 1
c) I can’t guess the number
d) None of the mentioned

Answer: b
Explanation: The given condition is false so no other statement is executed.
Output: x is 1