From: "David A. Black" Date: 2009-02-01T21:03:56+09:00 Subject: Re: Object#singleton_class in Ruby 1.9? Hi -- On Sun, 1 Feb 2009, Sean O'Halpin wrote: > On Sat, Jan 31, 2009 at 8:03 PM, Thomas Sawyer wrote: > [snip] >> Consider this form in place of the usual 'class << self': >> >> class X >> extend Module.new { >> ... >> } >> end >> >> Not quite as elegant since we can't use do...end. But if #extend could >> take a block: >> >> class X >> extend do >> ... >> end >> end >> >> Then the issue becomes transparent. Even for regular objects: >> >> obj.extend do >> ... >> end >> > > I like this - how do you see it working alongside the proposed > #class_extension from a while ago? > > I guess #extend would work as above (i.e. defines singleton methods on > instances), where #class_extension (or #class_extend?) methods/modules > would both extend a class and be inherited by subclasses. I forget I wouldn't want to see 'extend' start to mean both adding a module to the lookup path, and adding methods to the singleton class, depending on the context. I guess obj.extend do ... could create an anonymous module, though I've never had an issue with just creating it with Module.new or using a named module. > where the discussions on module inheritance ended up. Would you have a > #module_extend method too or would #class_extension work for both > classes and modules (in which case it should be renamed or alased)? > >> This is not to say that a singleton_class/eigenclass method would never >> be of use, but it would certainly mitigate the need for it a great deal. >> (One might also take away from this that a better name for it, if it >> were given a method name, would be #extension, but I mention that only >> as an aside.) > > I think you're onto something here - conceptually, #extend, singleton > methods and the-class-that-cannot-be-named are closely related but you > wouldn't know that from their names (or lack of them). They're related conceptually but they also fit into the object model nicely: every method is defined in a class or module; every object has a lookup path of classes and modules. I know Matz has said that the main thrust of per-object behavior is per-object behavior, and that the way it's implemented (singleton class, which, like other classes, can include modules) is secondary, but there's a tremendous advantage to having it blend into the overall landscape, I think. I've seen literally hundreds of "Ah ha!" moments where people suddenly grasp the whole per-object thing because once you get the idea of every object having a singleton class, you don't have to learn anything else new (with regard to #extend, etc.). David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!