From: dblack@... Date: 2006-07-13T20:24:03+09:00 Subject: Re: re-define class method Hi -- On Thu, 13 Jul 2006, David Chelimsky wrote: > On Jul 13, 2006, at 5:33 AM, dblack@wobblini.net wrote: > >> On Thu, 13 Jul 2006, David Chelimsky wrote: >> >>> thing_singleton_class = class << Thing; self; end >>> thing_singleton_class.send(:define_method, :class_method, proc { >>> "replaced" }) >>> >>> Thing.class_method >>> => "replaced" >> >> Don't forget that you can do this much more concisely (unless you have >> a specific need to go the long way round): >> >> def Thing.class_method >> "replaced" >> end > > Thanks David. I definitely appreciate the conciseness of this, and will use > that when I know the type. The problem I'm working on requires a solution to > replacing singleton methods on arbitrary types at runtime, so I think I have > to stick w/ the more cryptic version. Unless you have a different suggestion > - I'm just getting my head wrapped around metaprogramming and singleton > classes, so all suggestions are most welcome. There's an intermediate version, which might be usable depending on how much you know in advance: class << Thing def class_method "replaced" end end When you need a less concise version, because you're determining things more dynamically, I would personally tend to use class_eval and define_method without send: meth = "class_method" l = lambda { "replaced" } (class << Thing; self; end).class_eval { define_method(meth,&l) } And hopefully we'll eventually have a Kernel#singleton_class method to make it all a little neater :-) David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy http://www.manning.com/black => RUBY FOR RAILS (reviewed on Slashdot, 7/12/2006!) http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log dblack@wobblini.net => me