Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Get a temporary context with ‘self.dup.instance_eval’

By Peter Cooper / August 31, 2006

def foo
  'bar'
end

module M
  def foo
    'baz'
  end
end

puts "should be 'bar': #{foo}"

self.dup.instance_eval do
  extend(M)
  puts "should be 'baz': #{foo}"
end

puts "should be 'bar': #{foo}"

Garry Dolley worked out some interesting Ruby-fu to create a temporary execution context on the fly using self.dup.instance_eval. Any other tricks we could use this for?

Comments

  1. Chris says:

    That's real hot. Real hot.

Other Posts to Enjoy

Twitter Mentions