MC logo

Case Expression

  Ruby Example Code

<<For Loop case1.rb Iterators>>
for i in (1..10)
    rno = rand(100) + 1
    msg = case rno
        when 42: "The ultimate result."
        when 1..10: "Way too small."
        when 11..15,19,27: "Sorry, too small"
        when 80..99: "Way to large"
        when 100:
                print "TOPS\n"
                "Really way too large"
        else "Just wrong"
    end
    print "Result: ", rno, ": ", msg, "\n"
end
See:Ruby User's GuideRuby Manual

The ruby case statement is similar to the C/C++/Java switch, but more directly related to the similar (and superior) structures from Pascal and Ada. First, it assumes that each case ends where the next one starts, without needing a break to terminate a case. Secondly, each case can be expressed rather generally, with a single value, a range of value, or a list containing some of each.

For this example, I'm using the fact the control statements have a return value. That's not special to cases, and their value can be used or not, just as ifs.
<<For Loop Iterators>>