From: Mauricio Fernandez Date: 2006-08-13T19:03:43+09:00 Subject: Re: A use case for an ordered hash On Sun, Aug 13, 2006 at 06:31:07PM +0900, Matt Todd wrote: > Absolutely... an Array is perfect for ordered information. > > actions = [ > { /abcd/ => lambda { do_this } }, > { /xyz/ => lambda { do_that } }, > { /abc/ => lambda { other } } > ] > > Then, all you do is... > > actions.select { |action| action[input] } > > where input = /xyz/ you will receive the appropriate hash (key and > Proc) in an array. So, to do something with that, you could... > > actions.select { |action| action[input] }.first[input].call > > which calls the Proc associated with the matching element. That's not what he wants though (the point is matching against the Regexp --- Hash#[] doesn't buy you anything there). Maybe require 'enumerator' def ASSOC(x); x.enum_for(:each_slice, 2).to_a end actions = ASSOC [ /abcd/, lambda{ 1 }, /xyz/, lambda{ 2 }, /abc/, lambda{ 3 } ] # Then he's got to def run(command, actions) actions.each{|re, action| return action[command] if re =~ command} nil end run("abcdef", actions) # => 1 run("abcf", actions) # => 3 # But this would be nicer class Array def cassoc(x) # "case assoc" each{|arr| return arr if arr[0] === x} nil end end re, action = actions.cassoc("abcdef") action and action.call # => 1 re, action = actions.cassoc("abcx") action and action.call # => 3 -- Mauricio Fernandez - http://eigenclass.org - singular Ruby