From: dblack@... Date: 2007-02-23T13:22:53+09:00 Subject: Re: Ruby's "case" doesn't behave like a normal switch Hi -- On Fri, 23 Feb 2007, 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. I don't consider that a problem. If all languages had to behave exactly the same way, there would only be one language, and we'd all get bored :-) > 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 ? It's very dangerous. Remember that changing Array#=== changes it everywhere. There may be places in Ruby itself, or in other libraries you're using, that depend on the original behavior. David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)