From: Florian Gross Date: 2004-09-24T05:54:45+09:00 Subject: Re: Newbie: Case statement Markus wrote: >>>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. Also the 'pointer' part is a bit misleading. It's just a normal object. In Ruby one can create lambdas (kinda like blocks turned into Objects) and .call them later one. They remember their creation context just like blocks do. Here's a sample of a higher-order function (a function returning another function) -- note that the argument of the outer lambda, 'a', will still be available when the returned lambda is called. times_fun = lambda do |a| lambda { |b| a * b } end two_times_fun = times_fun.call(2) two_times_fun.call(4) # => 8 And greedy_case() doesn't even really need a lambda. Anything that has a #call method will work. Here's a bad sample: result = greedy_case(obj, String => obj.method(:reverse), Numeric => obj.method(:to_s)).values.first >>- 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? > [Detailed explanation] I couldn't have explained this better. Thank you. :) Regards, Florian Gross