From: Markus Date: 2004-09-24T04:30:26+09:00 Subject: Re: Newbie: Case statement On Thu, 2004-09-23 at 12:09, Graham Foster wrote: > > Yup, you can use this as a case that checks all options: > > > > def greedy_case(obj, cases) > > cases.find_all do |condition, action| > > condition === obj > > end.inject(Hash.new) do |hash, (condition, action)| > > hash[condition] = action.call; hash > > end > > end > > OK - Does this do the following (roughly) > - passes the input variable (x) and a hash of ranges and pointers to > functions (C speak) More or less, though there is no requirement that the conditions be ranges; the could be values, classes, regexp's, etc. as needed. > - No idea what end.inject means, but the effect is to iterate through > the hash of "ranges" (or presumably eny condition), and for each > match (determined by === must look this up) execute the inline > function (block). > - What is the last hash for? Actually, the find_all takes the hash of cases and reduces it to those that apply to this obj. The inject then iterates over this hash of conditions (keys) and actions (values) and produces a new hash (which will be the result) with the same keys but the _results_ of the actions as the values. [1,3,17].inject(0) { |running_total,value_to_add| running_total+value_to_add } does: 0+1+3+17; the argument to inject is the "seed value" and the block takes a pair of values and "combines" them in some way. In this case he combines a hash and a condition/action pair by adding the result of the action to the hash with the condition as the key. > Roughly right? Yep. -- MarkusQ