Ruby - Alternative Case Syntax


There is an alternative form of the case statement.

Each when section can perform some arbitrary test and execute one or more lines of code.

No case variable is required.

Each when section returns a value that is the result of the last piece of code that's evaluated.

This value can be assigned to a variable preceding the case statement:


level = 2000000 
season = 'summer' 

happy = case # from  w ww.  j  av a 2 s .  com
    when level > 10000 && season == 'summer' then 
        puts( "Yes, I really am happy!" ) 
        'Very happy' 
    when level > 500000 && season == 'spring' then 'Pretty happy' 
        puts( 'miserable' ) 
puts( happy ) #=> 'Very happy'


Related Topic