From: HarryO Date: 2001-07-09T01:09:51+09:00 Subject: [ruby-talk:17501] Re: Aliases for class methods > Let's look at another example > > class File > alias original path > def path > ... > end > end > > f = File.new(...) > puts f.path > > > Here we've defined an alias for the _instance_ method 'path'. These > instance methods are defined without a prefix in the class body, and are > invoked by sending their name to instances of class File ('f' in this > case). Ah! I think I see now why what I suggested was wrong. Of course, any alias defined purely inside "class Fred ... end" can only be for instanc methods, not for class methods! "File" is an instance of type Class. Doing the "class << self ... end" scoping is adding the alias to that Class object. That makes a lot more sense now. > So, aliasing works on instance methods, and the class methods of file > are instance methods of File's metaclass, When you say "File's metaclass" do you just mean the Class instance that contains the definition of "File"? Ie, that there's not a specific superclass for File and another for FixNum etc. They all have the same superclass (ie "Class"). >... So, I could define my alias for File's methods using > > class < alias original open > def open(*args, &b) > puts "Opening" > File.original(*args, &b) > end > end Actually, that way of defining File's class method "open" makes more sense to me than the "normal" way of using "File.open" inside "class File ... end" and makes all the class-level definitions consistent. I guess, though, that since one often wants class methods, having a shortcut syntax for them is convenient. Class-level aliases are probably a lot rarer. > The real trick to understanding all this metaclass stuff is to realize > that it as actually simper than it seems :) There are no special cases. Yes, I see that now (although, I think one could consider the "def File.open" syntax to be a special case). > All objects have a class. Classes are objects. So classes must have a > class. The first couple of paragraphs of chapter 19 really do say it > all. I'll definitely have a careful read of chapter 19 sometime soon. It sounds like understanding its contents will provide a solid context for grasping how a lot of things work in Ruby. Thanks for the lucid explanation!