Jano Svitok
8/8/2007 2:20:00 PM
On 8/8/07, Shai Rosenfeld <shaiguitar@gmail.com> 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?)
You could possibly do something like the following, but it's pretty dangerous:
class Object
alias_method :old_case_equal, :===
def ===(other)
case other
when Array:
other.include? self
else
old_case_equal(other)
end
end
end
puts case [3, 45, 6, 'abc']
when 1: 'no good'
when 3: 'good!'
when 'lolo': 'no good'
end
I.e. case calls === on each when condition, so if you define proper
=== that will not break other things, you're done.
when you run
case a
when b: ...
when c: ...
end
ruby will evaulate
b === a, i.e. b.===(a)
c === a, i.e. c.===(a)
J.