Brian Candler
9/30/2004 8:13:00 PM
> But "factoring out the variable" largely misses the point. Try it
> with a concrete example:
>
> def criterion(&b)
> Proc.new :===,&b
> end
>
>
> non_numeric = criterion {|x| !(x.is_a? Numeric}
> negative = criterion {|x| x < 0}
> prime = criterion {|x| ...
> case n
> when non_numeric ...
> when negative ...
> when Float ...
> when prime ...
> else ...
> end
Fair enough. I'd make those criteria constants, rather than local variables
- perhaps in all-caps to avoid confusion with classes like Float.
However, I notice you decided to wrap Proc.new(:sym) in a method - which
suggests to me that there is little benefit from having the new feature in
Proc.new, as your 'criterion' method could just as well have done the work
there.
Perhaps it makes more sense in this particular example to subclass Proc,
giving a "Proc which has an === method for use in case statements":
class Criterion < Proc
def ===(other)
call(other)
end
end
NEGATIVE = Criterion.new {|x| x < 0 }
[1,3,-4].each do |v|
puts v
case v
when NEGATIVE
puts "Negative!"
end
end
Regards,
Brian.