Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
ternary
operator

What is the ternary operator in Ruby?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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:​

marks = 65
if marks > 40
puts "Pass!"
else
puts "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 = 85
if marks > 80
puts "Distinction!"
elsif marks > 40
puts "Pass!"
else
puts "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 = 65
grade = '';
marks > 40 ? (grade ='Pass!'; puts "Welldone!")
: (grade = 'Pass!'; puts "Better luck next time.");
puts grade
svg viewer

RELATED TAGS

ruby
ternary
operator
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring