Ruby? Operator
In Ruby, the ? operator is a ternary operator. It is used as a shorthand for an if…else statement. The syntax is as follows:
In this case, the condition is evaluated as either true or false. If the condition is true, the expression before the : is executed. Otherwise, the expression after the : is executed.
We can demonstrate this by using an example as shown below:
puts x > 0 ? "positive" : "negative"
In this case, the code will test whether the value of x is greater than 0. If true, the block will print positive. Otherwise, it will print negative.
positive
=> nil
The same case applies if the value is negative as shown:
irb(main):004:0> puts x > 0 ? "positive" : "negative"
negative
=> nil
You can also chain multiple conditions using the ? operator as shown in the example below:
puts x > 0 ? "positive" : x == 0 ? "zero" : "negative"
In this case, the query will test the value of x against three conditions. If the value is greater than 0, the code will print positive. If the value is equal to zero, the code will print the string zero. And finally, if neither of those conditions are true, the code will print “negative.”
We can also use the ternary ? operator in a method and variable names. This referred to as the “Safe Navigation Operator”, or &. operator and it is used to check if the receiver of the method call is not nil before calling the method.
x&.upcase # HELLO
y = nil
y&.upcase # nil
We can also use the ternary operator to assign value as demonstrated below:
y = x > 0 ? 1 : -1
In this case, y will hold the value of 1.
Conclusion
This covered the basics of working with the Ruby ternary operator to perform various operations. It is worth noting that the ternary operator has a lower precedence than most other operators in Ruby. Hence, you may need to use parenthesis to ensure that the expressions are evaluated in the intended order.
Although the ternary operator is suitable for quickly setting up a conditional statement, it does not provide good code readability. Hence, we recommend using the traditional if…else block where necessary.