Forum: Ruby Adding a method to a single object

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
76e4ed15535e84ddbb630828dd253c8f?d=identicon&s=25 Marco Lange (Guest)
on 2006-01-09 03:04
(Received via mailing list)
Hi,

how is it possible to add a method to a single object programatically?
E.g. I want to write a method

class Object

   def rename_method(old_id, new_id)
     ...
   end

end

The method shall rename a method for a specific instance of any class,
e.g. the following should be possible:


a = 5
5.rename_method :times, :veces

5.times { ... }
   -> Error, Method "times"does not exist

5.veces { ... }
   -> Expected behaviour

I already succeeded in renaming methods for whole classes, but for a
single instance?

I do not really have a use case for such a method, but it is fun
learning about the object model in Ruby.

Best regards,
    Marco
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-01-09 03:22
(Received via mailing list)
Hi --

On Mon, 9 Jan 2006, Marco Lange wrote:

> Hi,
>
> how is it possible to add a method to a single object programatically?

def obj.meth
   ...
end

(and a few other ways, but that's the simplest)

> The method shall rename a method for a specific instance of any class, e.g.
>  -> Expected behaviour
>
> I already succeeded in renaming methods for whole classes, but for a single
> instance?

Keep in mind that a single instance has a class of its own -- its
singleton class -- as well as its class of origin.  If you do the
renaming in the singleton class, it will affect only that object.

Have a look at this example, and see if it helps:

   class C
     def m
       puts "In the method"
     end
   end

   c = C.new
   c.m   # In the method

   class << c   # "<< c" invokes the singleton class of c
     alias n m
     undef_method("m")
   end

   c.n  # In the method
   c.m  # error -- no such method

Hmmm... one problem is that Fixnums don't have singleton classes, so
this wouldn't work for 5.  Anyway, maybe it will give you ideas :-)


David

--
David A. Black
dblack@wobblini.net

"Ruby for Rails", from Manning Publications, coming April 2006!
http://www.manning.com/books/black
This topic is locked and can not be replied to.