From: Paul Brannan Date: 2004-07-03T05:48:45+09:00 Subject: Re: define_method to add a Class method? On Sat, Jul 03, 2004 at 04:53:26AM +0900, Sean O'Dell wrote: > I'd stick with eval; it does the job. Something like this should work > just fine: Using eval doesn't allow the method to be executed in the context in which it was created, which is what define_method allows. You can make it work by assigning a proc to a variable and then calling that proc from the eval'd code, but that's overkill, since define_method does the job: class Foo s = class << self; self; end l = 42 # local variable s.class_eval do define_method(:foo) do puts "here: #{l}" end end end Foo.foo #=> here: 42 We first get the singleton class and assign it to s, then call define_method for the singleton class (we could call define_method from inside the class << self block, but then we wouldn't have access to local variables). Paul