Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The Conditional: ?: Operator
2.1.
Syntax:
2.2.
Examples:
2.2.1.
Example 1:
2.2.2.
Example 2:
3.
Why use this operator?
3.1.
Example:
4.
Frequently Asked Questions
4.1.
What is the difference between the if-else statement and the conditional operator?
4.2.
What is the associativity of this operator?
4.3.
What are the drawbacks of using parentheses in this operator?
5.
Conclusion
Last Updated: Mar 27, 2024

The Conditional: ?: Operator in Ruby

Author Gurleen Kaur
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

The token or symbol used to define the operations performed on many operands is an operator. These operators may use one or more operands and perform different operations. There are sets of operators defined for each programming language, and similarly, Ruby has its own too. The operands can be literal or expressions, and operators try to convert them into higher expressions.

This article will explore the Conditional: ?: Operator in Ruby. This operator is the only ternary operator, i.e.; it uses three operands for its operation. Let us know more about it.

The Conditional: ?: Operator

This operator is the only operator in Ruby that uses three operands and is the ternary operator. It has three parts, out of which the first part is the condition, and the other two are the possible outcomes for the result of the condition.

We know that the condition may result in two outcomes which may be true or false. Hence, the other two parts have the code to be executed if the condition is correct. You will further understand this part when we will discuss its syntax.

Syntax:

Condition ? True : False

In the syntax given above, we have three parts. Let’s discuss them one by one.

First Part (i.e., Condition in this case): In this part, the user enters the required condition he wants to test and upon which he wants the desired outcomes.

Second Part (i.e., True in this case): If the given condition is true, the written code should be executed.

Third Part (i.e., False in this case): Written code should be executed if the given condition is false.

In this syntax,? and : are part of the syntax and must be there.

Examples:

Example 1:

x=3
#condition is true
x==3 ? ans=1 : ans=0
puts ans

Output:

1

Example 2:

x=2
#condition is false
x==3 ? ans=1 : ans=0
puts ans

Output:

0

This operator has relatively low precedence, and hence, it is not compulsory to put parentheses in the syntax. But, if the condition statements use the defined? Operator or the other outcomes use the assignment operators; in that case, parentheses are necessary.

It is also necessary to put parentheses when methods used in the condition part end with an identifier. In this case, you can even put spaces between the syntax for proper explanation and correct working of the operator. Look at the example below for an explanation:

a==2 ? b : c          # This is legal 
2==a ? b : c          # Syntax error: a? is interpreted as a method name 
(2==x) ? b : c        # Okay: parentheses fixes the problem 
2==a  ? b : c         # Spaces also eliminate the problem

This operator is right-associative, so the rightmost ones are grouped if these are used multiple times. For example:

v ? w : x ? y : z                               # The expression 
v ? w : (x ? y : z)                             # is solved like this

This is how this operation works in Ruby.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why use this operator?

You would have seen above the working of this operator and noticed it is the compact version of the if-else condition. It simplifies the code in a single line and therefore is used to short the number of code lines.

Example:

x=3
if(x>7)
    puts "true"
else
    puts "false"
end

Output:

false

This code uses multiple lines, but using the conditional operator reduced them. Check the code below for the simplified version.

x=3
x>7 ? res="true" : res="false"
puts res

Output:

false

Due to this reason, conditional operators should be used.

Frequently Asked Questions

What is the difference between the if-else statement and the conditional operator?

If-else statement allows the execution of multiple statements, whereas the conditional operator allows only a single statement as an outcome.

What is the associativity of this operator?

It has right-to-left associativity.

What are the drawbacks of using parentheses in this operator?

It reduces the readability of the code and further takes away the benefits of using this operator.

Conclusion

In this article on Ruby operators, we have extensively discussed the conditional operator. We started with a brief introduction of the operators, the syntax, and why to use them, along with an example.

Check out this article - Balanced Parentheses

You can refer to our guided paths given on Coding Ninjas Studio to train yourself in Competitive ProgrammingData Structures and AlgorithmsSystem DesignJavaScript, and many more! Also, if you want to test your competency in coding, look into the several mock test series and participate in the contests organized on Coding Ninjas Studio! However, if you have just started your learning process and are simply looking for tech giants like Amazon, Microsoft, Uber, etc. It would help to look at the interview experiences, problems, and interview bundles for placement preparations.

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Previous article
Ranges and FlipFlops in Ruby
Next article
Assignment Operators in Ruby
Live masterclass