Ruby - Alternative Case Syntax

Introduction

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:

Demo

level = 2000000 
season = 'summer' 

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

Result

Related Topic