From: Florian Gross Date: 2004-09-23T21:04:33+09:00 Subject: Re: Newbie: Case statement Graham Foster wrote: > As a newbie I'm confused about the Case construct. All the > documentation I've found states "case operates by comparing the > target with EACH of the expressions after the When keyword" > This does NOT appear to happen, as only the first match is ever > actioned, so overlapping WHEN cases are skipped. > I assume this is expected behaviour? (I'm ex-C - and was looking for > fall-through behaviour) Yup, you can use this as a case that checks all options: def greedy_case(obj, cases) cases.find_all do |condition, action| condition === obj end.inject(Hash.new) do |hash, (condition, action)| hash[condition] = action.call; hash end end def test(x) greedy_case(x, 1 .. 2 => lambda { puts "In A" }, 1 .. 3 => lambda { puts "In B" }, 2 .. 4 => lambda { puts "In C" }) end test(2) Regards, Florian Gross