From: Jim Haungs Date: 2004-11-04T12:28:46+09:00 Subject: Re: Hashes and Blocks (Syntactical/Feature question) What's a hashtable with names pointing to code blocks? Hmm... Sounds like a class! What you're trying to do is an example of the State pattern, which is often implemented with sensibly-named states (as opposed to the numbers in the example here). The state names are really method names; you perform the operation for some state X by sending the X message to an instance of the State class. The class can also encapsulate the current state of the machine, track state transitions, or whatever. And if you need multiple instances of the state machine, you just create a new instance of the State class. With the hash table scheme, the cohesion is poor because the current machine state is separated from the operations on that state. On Sat, 30 Oct 2004 14:31:19 +0200, "Robert Klemme" wrote: > >"Gavin Sinclair" schrieb im Newsbeitrag >news:193-2098986814.20041030113810@soyabean.com.au... >> On Saturday, October 30, 2004, 11:29:20 AM, Pete wrote: >> >>> I haven't been able to find any documentation on the syntax for a >>> certain feature, and am not sure the feature exists. What I would like >>> to do is add a block of code to a hash, so I could do something like >>> this: >> >>> state = 0 >>> states = { >>> 0 => { puts "State 0"; state = 1 }, >>> 1 => { puts "State 1"; state = 0 } >>> } >> >> It's pretty easy: >> >> state = 0 >> states = { >> 0 => lambda { puts "State 0"; state = 1 }, >> ... >> } >> >> while a_condition >> states[state].call >> end > >And you can even define default behavior: > >state = 0 >states = Hash.new( lambda { puts "fallback" } ).update( > 0 => lambda { puts "State 0"; state = 1 }, > 1 => lambda { puts "State 1"; state = 0 } >) > >loop do > states[rand 100].call >end > >or even (for individual fallbacks) > >states = Hash.new { |h,k| h[k] = lambda { puts "fallback for #{k}" } } >.update( > 0 => lambda { puts "State 0"; state = 1 }, > 1 => lambda { puts "State 1"; state = 0 } >) > >>> 10.times {|i| states[i].call } >State 0 >State 1 >fallback for 2 >fallback for 3 >fallback for 4 >fallback for 5 >fallback for 6 >fallback for 7 >fallback for 8 >fallback for 9 >=> 10 > >Kind regards > > robert >