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.