Ruby - Short-form notation for if..then..else

Introduction

Ruby has a short-form notation for if..then..else.

A question mark ? replaces the if..then part and a colon : acts as else.

Formally, this may be known either as a ternary operator or as a conditional operator.

< Test Condition > ? <if true do this> : <else do this> 

For example:

x == 10 ? puts("it's 10") : puts( "it's some other number" ) 

When the test condition is complex, you should enclose it in parentheses.

If you put a newline before the ? or the :, you will generate a syntax error. This is an example of a valid multiline code block:

(aDay == 'Saturday' or aDay == 'Sunday') ? 
   daytype = 'weekend' : 
   daytype = 'weekday' 

Here's another example of a longer sequence of if..elsif sections followed by a catchall else section.

This time the trigger value, i, is an integer:

Demo

def showDay( i ) 
   if i == 1 then puts("It's Monday" ) 
   elsif i == 2 then puts("It's Tuesday" ) 
   elsif i == 3 then puts("It's Wednesday" ) 
   elsif i == 4 then puts("It's Thursday" ) 
   elsif i == 5 then puts("It's Friday" ) 
   elsif (6..7) === i then puts( "It's the weekend! " ) 
   else puts( "That's not a real day!" ) 
   end #  w  w  w. j  av a 2 s  . c  om
end

The range (6..7) matches the two integer values for Saturday and Sunday.

The === method tests whether a value (here i) is a member of the range.

In the previous example, the following:

(6..7) === i 

could be rewritten as this:

(6..7).include?(i) 

The === method is defined by the Object class and overridden in descendant classes.

Its behavior varies according to the class.

As you will see shortly, one of its fundamental uses is to provide meaningful tests for case statements.

Related Topic