From: Eleanor McHugh Date: 2008-05-07T00:58:20+09:00 Subject: Re: I know this code is not very 'ruby' On 6 May 2008, at 15:48, Robert Klemme wrote: > 2008/5/6 Eleanor McHugh : >> Remember that case statements are expressions, hence: >> >> def discount(discount_category) >> case discount_category >> when 1 : 40 >> when 2 : 100 >> when 3 : 160 >> else discount_out > > I guess this should read > > else 0 That's what happens when I write code before my second cup of tea of the morning ;) > I was going to suggest something similar, i.e. use more verbose > category "names". If categories are read from somewhere they could be > mapped on input. > > But, as Todd also mentions, this cries for a Hash. With a Hash method > #discount is basically superfluous. > > DISCOUNT = Hash.new(0).update( > :friend => 40, > :vet => 100, > :super_vet => 160 > ).freeze > > Then a method call essentially becomes > > DISCOUNT[:foo] > > instead of > > discount :foo I'd probably use a Hash as well for a trivial mapping like this, but I thought it was more instructive to just abolish the unnecessary variable seeing as Tim clearly didn't realise that Ruby uses a case expression rather than a case statement. And of course if the discount were to rely on several parameters then the case expression form might well be much easier to maintain. Ellie Eleanor McHugh Games With Brains http://slides.games-with-brains.net ---- raise ArgumentError unless @reality.responds_to? :reason