From: Robert Klemme Date: 2003-06-03T17:10:33+09:00 Subject: Re: Dynamically scoped variables "Tanaka Akira" schrieb im Newsbeitrag news:87k7c3mxma.fsf@serein.a02.aist.go.jp... > In article <3EDC224D.90803@pragprog.com>, > Dave Thomas writes: > > > Just as a bit of fun I posted a piece on implementing dynamically scoped > > variables in Ruby at > > > > http://pragprog.com/pragdave/Tech/Random/StackContext.rdoc,v > > > > I'm sure there are easier ways. I just hacked this one out, so I'm happy > > to be humiliated with better solutions. > > def with_context(params) > Thread.current[:dynamic] ||= [] > Thread.current[:dynamic].push params > begin > yield > ensure > Thread.current[:dynamic].pop > end > end > > def find_in_context(name) > Thread.current[:dynamic].reverse_each {|params| > return params[name] if params.has_key? name > } > raise "Can't find context value for #{name}" > end Very nice indeed! Couldn't we save one lookup by doing def with_context(params) ( Thread.current[:dynamic] ||= [] ).push params begin yield ensure Thread.current[:dynamic].pop end end Regards robert