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

svg viewer
  • The value of the condition determines which value is used.
  • The value after the ? is returned if the condition returns true.
  • The value after the : 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 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.​

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 = 65
grade = '';
marks > 40 ? (grade ='Pass!'; puts "Welldone!")
: (grade = 'Pass!'; puts "Better luck next time.");
puts grade
svg viewer
Copyright ©2024 Educative, Inc. All rights reserved