From: Pit Capitain Date: 2004-02-27T04:11:55+09:00 Subject: Re: Callback Han Holl wrote: > The following code works, but I was wondering if the creation of the @obj > instance variable is really necessary? No, you don't need the instance variable (see below). > class A > def callback(name, obj) Original version: > @obj = obj > eval("def #{name}; @obj.keys; end") Alternative 1: self.class.send :define_method, name, proc { obj.keys } Alternative 2: class << self; self; end.send :define_method, name, proc { obj.keys } > end > end > > class B > attr_reader :keys > def initialize(k, cb) > @keys = k > cb.callback('cassette', self) > end > end > > a = A.new > g = B.new([1,2,3], a) > puts a.cassette Alternative 1 behaves more or less like your original version. The drawback of both of them is that the method is defined in class A, but works only in one instance of A. Alternative 2 defines the method only in the one instance passed to callback. Add puts A.new.cassette to the tests to see the difference. Regards, Pit