Ruby

Meaning of Double Question Mark in Ruby

When working with Ruby code bases, you may encounter a syntax that uses double question marks. In this tutorial, we will summarize what these operators mean and how they work in the context of usage.

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:

condition ? action_if_true : action_if_false

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:

x = 5
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.

irb(main):002:0> puts x > 0 ? "positive" : "negative"
positive
=> nil

The same case applies if the value is negative as shown:

irb(main):003:0> x = -5
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:

x = 5
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 = "hello"
x&.upcase  # HELLO
y = nil
y&.upcase # nil

We can also use the ternary operator to assign value as demonstrated below:

x = 5
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list