The Question Mark Operator in Ruby on rails

By: Brian Marick Viewed: 153181 times    

You’ll often find yourself selecting between two alternative values for a variable. That can be done like this:

if input < 0

output = 0


output = input


But it seems wrong to take up five lines for such a simple idea. You can reduce it to two by picking one of the values and then possibly overriding it:

output = input

output = 0 if input < 0

But it’s a little confusing for the code to do something and then immediately say, “Wait! I didn’t mean that!” So there’s a compact version of if for just this purpose:

output = (input < 0) ? 0 : input

You can read that as “if input is less than zero, then return 0, else return whatever object input names.”

This ?: construct is called either the question mark operator or, more question mark operator often, the ternary operator. (“Ternary” because it uses three expres- ternary operator sions, unlike operators such as +, which have two and are called binary operators.) binary operators

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)

Comment on this tutorial