Todd Benson
8/14/2008 12:29:00 AM
On Wed, Aug 13, 2008 at 6:59 PM, Ryan Davis <ryand-ruby@zenspider.com> wrote:
> I agree that your second example doesn't feel right... I prefer altering
> your original example:
>
> case amount
> when 25..50: 42
> when 51..66: 78
> when 90..123: 99
> else amount < 25 ? 100 : 200
> end
Don't use this; it's just for fun...
my_number = 57
begin
[25, 51, 67, 90, 123].zip([100, 42, 78, 0, 99]).select {|a| a[1] if
my_number < a[0]}.first[1] rescue 200
end
Two things.
1. It's generally not good form to use a rescue for program logic
2. I'm surprised that no one saw the fundamental problem in using
ranges. We're looking at a line that has divisions, not pieces that
may or may not overlap. I suppose if you were clever, you could make
it work and have it behave almost the way you want it to.
I'd go with dividers instead of ranges. You could build your ranges
automagically with a list of the divisions, I suppose.
Even though at first glance it seems verbose, I do like Ara's
solution. And Ryan Davis' crack is really simple and succinct. Like
them both!
Todd