From: Brad Phelan Date: 2007-08-08T23:29:58+09:00 Subject: Re: case statement Brad Phelan wrote: > Shai Rosenfeld wrote: >> Alex Young wrote: >>> Shai Rosenfeld wrote: >>>> end >>>> >>>> ((i.e, whatever value is included in the array)) >>>> ...how do i do this? >>> Does the Array#include? method do what you need? Perhaps a more >>> fleshed-out example might help? >> >> Array#include is EXACTLY what i need, but syntaxtetically (if u get >> the drift) i'm not sure how to do it: >> >> case [3, 45, 6, 'abc'].inlcude? >> when 1: 'no good' >> when 3: 'good!' >> when 'lolo': 'no good' >> end >> >> (the above doesn't work. it's gives a 'not enough arguments' error. >> how do i do it correctly?) > > Here's is a little trick that works > > class Casey > def initialize(o) > @o = o > end > def method_missing(name) > CaseyMethod.new(@o, name) > end > end > > class CaseyMethod > def initialize(o, m) > @o = o > @m = m > end > def ==(other) > @o.send(@m, other) > end > end > > class Object > def casey > Casey.new(self) > end > end > > > case [2,3,4].casey.include? > when 1 > puts "a" > when 2 > puts "b" > else > puts "c" > end > > -- > Brad Phelan > http://xtargets.com The problem with the above is that I don't think it does what you want. It breaks out after it finds the first match and doesn't try to match any further. If more than one *when* expression matches only the first block is executed. -- Brad Phelan http://xtargets.com