Ruby - === Method is used in case when clause

Introduction

The when tests on an object used in a case statement are performed using the === method.

The === method returns true when an integer forms part of a range.

A when test returns true when an integer variable in a case statement forms part of a range expression:

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

Demo

i = 6
case( i ) # from w  w w  . ja v a2s  . com
    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