O'Reilly logo

The Book of Ruby by Huw Collingbourne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Case Statements

When you need to take a variety of different actions based on the value of a single variable, multiple if..elsif tests are verbose and repetitive.

A neater alternative is provided by a case statement. This begins with the word case followed by the variable name to test. Then comes a series of when sections, each of which specifies a “trigger” value followed by some code.

This code executes only when the test variable equals the trigger value:

case.rb

case( i )
   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" )
   when (6..7) then puts( "Yippee! It's the weekend! " )
   else puts( "That's not a real day!" )
end

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required