Ternary operators are simply a short form of an if-else statement in one line.
As a concise alternative to simple if/else statements we can use the conditional or ternary ?: operator. It is the only ternary operator (three operands) in Ruby. It has the following basic structure:
(condition) ? (result if condition is true) : (result if condition is false)
The following sample will print “The variable is 10″ if var is equal to 10. Otherwise it will print “The variable is Not 10″.
Ruby evaluates the expression to the left of the question mark. If that expression is true then it returns the expression between the question mark and the colon, if the expression is false, it returns what comes after the colon.
1 2 3 4 5 6 7 8
The part before the question mark is the “if condition”. the part behind it is the code to be run if the condition matches. the “:” respresents “else”, and the code behind it the code to be run if the condition does not maztch.
1 2 3 4 5 6 7 8 9 10 11