From: Joel VanderWerf Date: 2003-06-03T16:16:55+09:00 Subject: Re: Dynamically scoped variables Dave Thomas wrote: > 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 And, a variant that allows nested contexts to be cumulative, at the cost of an additional outer wrapper around code that uses it. def with_context(params) finder, = catch(:context) { yield } finder.call(params) if finder end def find_in_context(name) callcc do |again| throw(:context, [proc {|params| if params.has_key?(name) again.call(params[name]) else again.call(find_in_context(name)) end }, name]) end end def use_dynamic_biding attempt, name = catch(:context) { yield } if attempt raise "Can't find context value for #{name}" end end def update_widget name = find_in_context(:name) color = find_in_context(:color) puts "<#{color}>#{name}" end def update_screen update_widget end use_dynamic_biding do with_context(:name => 'dave', :color => 'red') do with_context(:foo => 'bar') do update_screen end end end