From: Ben Tilly Date: 2001-03-04T10:45:18+09:00 Subject: [ruby-talk:11957] Re: singleton classes? "Christoph Rippel" wrote: > > > From: Ben Tilly [mailto:ben_tilly@hotmail.com] >[...] > > > >Sometimes it's simply a notational convenience. Othertimes, you > > >genuinely need to be able to add features to objects.[...] > > > > > >I have to admit I use this rarely, but it's always a nice solution to > > >have in your back pocket. > > > > I actually tried putting this in my back pocket a while > > ago, and failed. > > > > Can someone give me an example of how you would write a > > method that extends an object and gives it a new method? > > (I kept on seeing "nested method definition" warnings > > when I tried it the naive way.) I just found a way. I don't really like it, but I will live. >Since methods are not objects you will have hard time >doing this (I know you can create a method object but >this is not the same thing). You can do it with eval. >Probably the closed is the #extend method from Object - >for example. > >module Bla >def do_nothing >end >def also_useless >end > >x = Object.new >x.extend Bla > >x.do_nothing >x.also_useless > That was basically what was already shown by Dave. So you can have a limited list of modules around, and you can add modules to classes wherever you want. That isn't what I want. What I got to work was this: class SomeClass def add_hello (my_msg="Hello, world") eval <<-"end_eval" class << self def hello (msg="#{my_msg}") puts msg end end end_eval end end a = SomeClass.new b = SomeClass.new c = SomeClass.new a.add_hello b.add_hello "This works also" a.hello # Hello, world b.hello # This works also c.hello # Oops. :-) Ruby just really doesn't like seeing "def" as a key word within a method definition. Cheers, Ben _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com