From: "M. Edward (Ed) Borasky" Date: 2006-08-13T15:43:09+09:00 Subject: Re: A use case for an ordered hash Hal Fulton wrote: > There have been numerous occasions when I wanted an > ordered hash, but usually I can't remember to write > them down. > > Here's just one. > > Once I wanted a "dynamic case statement" of sorts. > I wanted to use procs as values in a hash. Something > like: > > actions = { /abcd/ => lambda { do_this }, > /xyz/ => lambda { do_that }, > /abc/ => lambda { other }} > > Then I could just iterate through the keys looking > for a match, then use that key to find the associated > proc and call it. > > However, I quickly noticed that this is no good. The > order of iteration is unpredictable. So I couldn't > guarantee that (for example) /abcd/ would be tested > before /abc/, and so on. > > So yeah, I ended up using an array of arrays. But it > just felt wrong. > > > Hal > > That sort of code is what Chuck Moore evolved into Forth. :) Seriously, though, isn't there a way to do this with a single array? Store the patterns followed by the lambdas in sequence. Find the first index that matches the pattern and take the lambda at [index+1]? Or two parallel arrays? I use two parallel arrays for this sort of thing a lot -- it's easy for me to read, given my FORTRAN background. :)