Introduction

Unlike case statements in C-like languages, there is no need to enter a break keyword when a match is made.

In Ruby, once a match is made, the case statement exits:

Demo

def showDay( i ) 
    case( i ) # w w w.j  a va  2s . co m
       when 5 then puts("It's Friday" ) 
       when 6 then puts("It's Saturday!" ) # the following never executes 
       when 5 then puts( "It's Friday all over again!" ) 
    end 
end 
showDay( 5 ) 
showDay( 6 )

Result

You can include several lines of code between each when condition.

You can include multiple values separated by commas to trigger a single when block, like this:

when 6, 7 then puts( "It's the weekend! " ) 

The condition in a case statement can be an expression like this:

case( i + 1 ) 

You can also use noninteger types such as a string.

when 1, 'Monday', 'Mon' then puts( "Yup, '#{i}' is Monday" ) 

Here is a longer example, illustrating some of the syntactical elements:

Demo

i = 4
case( i ) #   w  w  w . ja v a 2s. c o m
    when 1 then puts("It's Monday" ) 
    when 2 then puts("It's Tuesday" ) 
    when 3 then puts("It's Wednesday" ) 
    when 4 then puts("It's Thursday" ) 
    when 5 then puts("It's Friday" ) 
          puts("...nearly the weekend!") 
    when 6, 7   
          puts("It's Saturday!" ) if i == 6  
          puts("It's Sunday!" ) if i == 7  
          puts( "It's the weekend! " ) 
          # the following never executes 
    when 5 then puts( "It's Friday all over again!" ) 
    else puts( "That's not a real day!" ) 
end

Result

Related Topic