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.
?
is returned if the condition returns true
.:
is returned if the condition returns false
.The code below shows a simple If else
condition testing code and its equivalent code using the ternary operator:
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.
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