From: Guillaume Cottenceau Date: 2001-07-06T06:24:15+09:00 Subject: [ruby-talk:17348] Adding a method to a class at the top-level Comrades, I'm looking for the "fastest" way to add a method to an existing class, in a Ruby program. At first I thought there would be an elegant one-liner to do that, but unfortunately, the following adds a Class method, not an Instance method: def Demo.aClassMethod; end So the best way so far is: class Demo; def aclassMethod; end; end Which I don't find very elegant. The FAQ talks more or less about that problem: ----8<------------8<------------8<------------8<------------8<--------[1] http://www.rubycentral.com/faq/rubyfaq-8.html#ss8.11 8.11 Why are there two ways of defining class methods? You can define a class method in the class definition, and you can define a class method at the top level? class Demo def Demo.classMethod end end def Demo.anotherClassMethod end There is only one significant difference between the two. In the class definition you can refer to the class's constants directly, as the constants are within scope. At the top level, you have to use the Class::CONST notation. ----8<------------8<------------8<------------8<------------8<-------- My question is, why is it so? Maybe Matz thought that the most common case in adding one small method in the top-level would be a Class method rather than an Instance method. While I would think the contrary :-). Maybe we could find a smarter syntax to add an instance method at top-level when you want it to be short and elegant? (or maybe there is one and I'm missing it?) Ref: [1] matju style :-) -- Guillaume Cottenceau - http://mandrakesoft.com/~gc/