On Wed, 12 Apr 2006, Bill Kelly wrote:

>> harp:~ > cat a.rb
>> class BigDipper
>>   def self.little_dipper(a_symbol)
>>     define_method(a_symbol) { "#{a_symbol} is double-helix" }
>>   end
>>   def little_dipper(*a, &b) self.class.little_dipper(*a, &b) end
>> end
>> 
>> s_ = BigDipper.new
>> s_.little_dipper(:DNA)
>> p s_.DNA
>
> Thanks, Ara.  But is there any way to write it such that the
> method is only added to the specific instance of the class?
>
> I would like the following to return false:
>
>> q_ = BigDipper.new
>> p q_.respond_to?(:DNA)   # => false


   harp:~ > cat a.rb
   class BigDipper
     def little_dipper(a_symbol)
       singleton_class{ define_method(a_symbol) { "#{a_symbol} is double-helix" } }
     end
     def singleton_class &block
       sc = class << self; self; end
       sc.module_eval &block if block
       sc
     end
   end

   s_ = BigDipper.new
   s_.little_dipper(:DNA)
   p s_.respond_to?(:DNA)
   p BigDipper.new.respond_to?(:DNA)


   harp:~ > ruby a.rb
   true
   false

hth.

-a
-- 
be kind whenever possible... it is always possible.
- h.h. the 14th dali lama