Ruby Ternary Operator Tutorial

In this section, we will learn what the ternary operator is and how to use it in Ruby.

What is Ternary Operator in Ruby?

You can think of the ternary operator as the shorthand version of the Ruby if else statement.

The ternary operator is mainly used when we want to assign a value to a variable, but there’s a condition that it should be checked first and, based on the result of the condition, an appropriate operation should run.

Let’s jump into the syntax of this operator and then you’ll see how easy this operator is to use:

Ruby Ternary Operator Syntax:

condition ? true_expression : false_expression

`condition`: this is the expression that will be evaluated first and either returns true or false.

`true_expression`: this is the expression that will run if the result of the condition is true. The value here could be anything from calling a function to just a simple value.

`?`: between the condition of the ternary operator and the true_expression we put the question mark.

` false_expression`: this is the expression that will be run if the result of the condition becomes false.

`:`: between the `true_expression` and `false_expression` we put a colon to separate them from each other.

Example: using ternary operator in Ruby

puts "Please enter a value"

num = gets.to_i

result = num>100 ? "The value is greater than 100" : "The value is less than 100"

puts result

Output:

Please enter a value

44

The value is less than 100

How does ternary operator work in Ruby?

In this example, the condition of the ternary operator is to check and see if the value that the user has entered to the program is greater than the value 100 or less than that. Now because we’ve set the value 44, the result of the condition becomes false and so the false_expression which is `The value is less than 100` returned as a result of running this ternary operator.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies