What is the ternary operator in Ruby?
The conditional ternary operator assigns a value to a variable based on some condition. This operator is used in place of the if-else statement.
The operator first evaluates for a true or false value and then, depending upon the result of the evaluation, executes one of the two given statements.
Syntax
- The value of the condition determines which value is used.
- The value after the
?is returned if the condition returnstrue. - The value after the
:is returned if the condition returnsfalse.
The code below shows a simple If else condition testing code and its equivalent code using the ternary operator:
marks = 65if marks > 40puts "Pass!"elseputs "Fail!"end
Multiple ternary operators
Multiple else if statements can be used for variations of the same test case. The code below shows how these multiple variants can be implemented through both else if and ternary operators.
marks = 85if marks > 80puts "Distinction!"elsif marks > 40puts "Pass!"elseputs "Fail!"end
Multiple operations
Multiple operations can be performed with a ternary operator. The commands must be separated with ; (semicolons). The code below sets the value of the grade variable and then prints a message with the value if it fulfills the corresponding condition:
marks = 65grade = '';marks > 40 ? (grade ='Pass!'; puts "Welldone!"): (grade = 'Pass!'; puts "Better luck next time.");puts grade
Free Resources