0
0
Rubyprogramming~5 mins

Ternary operator in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary operator in Ruby?
The ternary operator is a short way to write an if-else statement. It uses the syntax: condition ? true_value : false_value.
Click to reveal answer
beginner
How does the ternary operator work in Ruby?
It checks the condition before the ?. If true, it returns the value after ? and before :. If false, it returns the value after :.
Click to reveal answer
beginner
Rewrite this if-else using a ternary operator:<br>
if age >= 18
  status = 'adult'
else
  status = 'minor'
end
status = age >= 18 ? 'adult' : 'minor'
Click to reveal answer
intermediate
Can the ternary operator be nested in Ruby?
Yes, you can nest ternary operators, but it can make code hard to read. It's better to use if-else for complex conditions.
Click to reveal answer
beginner
What is a common use case for the ternary operator?
It is used for simple decisions to assign a value quickly without writing multiple lines of if-else statements.
Click to reveal answer
What does this Ruby code return?<br>
5 > 3 ? 'yes' : 'no'
A'no'
B5
C'yes'
D3
Which symbol separates the true and false parts in a ternary operator?
A?
B!
C;
D:
What is the output of this code?<br>
puts (10 == 10 ? 'Equal' : 'Not equal')
ANot equal
BEqual
C10
DError
Is this a valid ternary operator usage in Ruby?<br>
result = condition ? do_something : do_something_else
AYes, it's valid
BNo, syntax error
COnly if condition is true
DOnly if condition is false
Why might you avoid nesting ternary operators?
AThey make code hard to read
BThey run slower
CThey cause syntax errors
DThey are not supported in Ruby
Explain how the ternary operator works in Ruby and give a simple example.
Think of it as a short if-else in one line.
You got /6 concepts.
    Describe a situation where using a ternary operator is better than an if-else statement.
    When you want to assign a value quickly based on a condition.
    You got /4 concepts.