From: Kjell Olsen Date: 2007-02-23T11:23:03+09:00 Subject: Re: Ruby's "case" doesn't behave like a normal switch Check this out for making your case statements work: http://redhanded.hobix.com/bits/wonderOfTheWhenBeFlat.html "Consider Olympic ice dancing out-graced!" -kjell On Feb 22, 2007, at 7:55 PM, Guillaume Nargeot wrote: > The problem with ruby is that you can't use a switch as it behaves > with many > other languages like C, php, etc. > > For example, you want to convert the following peace of code to ruby: > > switch (x) { > case 1: > case 2: > # do something > break; > case 3: > # do some other thing > break; > default: > } > > it seems you can do it with the following code: > > case x > when 1..2 > # do something > when 3 > # do some other thing > else > end > > But when it comes to strings, you would like to be able to do simply: > > case x > when "this" > when "that" > # do something common to "this" and "that" > when "nothing" > # something different > end > > The problem is that you can't, because of the fact the "break" is > implicit > in > the ruby language. > The fact is that you don't want to rewrite the same code two times. > Of course, you would be able to right your code into a function, > and then > just > write: > > case x > when "this" > func_this_that() > when "that" > func_this_that() > when "nothing" > # something different > end > > But if again, you don't want to relay on a function call, here's a > solution > I thought about. > > This is not perfect, because you have to change your syntax, but it > might be > quite useful in some cases. > > # Redefine the === method of the Array class, that is used to match > the > argument > # of the "case" directive. > class Array > # Return true if self contains any element of the given parameter. > def ===(o) > o.each do |e| > return true if self.include?(e) > end > false > end > end > > # Example 1 > x = ["case4"] > > case x > when ["case1", "case2"] > puts "first case" > when ["case3", "case4", "case5"] > puts "second case" > when ["case6"] > puts "third case" > else > puts "not matched" > end > > # Returns: "second case" > > # Example 2 > x = [6] > > case x > when [1, 2] > puts "first case" > when [3, 4, 5] > puts "second case" > when [6] > puts "third case" > else > puts "not matched" > end > > # Returns: "third case" > > What do you think about it ? >