Question
I have two questions:
- Does method
f_1
belong to the metaclass anonymous class? - Does method
f_2
belong to the anonymous class?
related to the following code:
car = "car"
class << car
def self.f_1
puts "f_1"
end
def f_2
puts "f_2"
end
end
Solution
Well, terminology is frangible, but FWIW I would say your class wasn't really an anonymous class. As for belonging, both of these methods only exist in the car object.
I'll be honest and admit that I'm a little vague about the difference between a class method and an instance method when the class is defined against an individual object like this -- I would guess that if there is any difference, it will be an obscure one that will make your code much harder to read ;)
Update: You might find this helpful, if you've not seen it before. (Personally, it makes my head hurt, but everyone's different...)
OTHER TIPS
Since ruby's own API uses the term "singleton class," I'd say the following are true:
f_1
is a class method on car's singleton class and can be called like this:car.singleton_class.f_1
f_2
is an instance method on car's singleton class and can be called like this:car.f_2
I was under the impression that an anonymous class is a class that has no name:
my_class = Class.new
my_class.name # => nil
However, the Pickaxe refers to it as a unnamed class rather than as an anonymous class.
A reformulation of Rob Davis' answer:
- The method-owner of
:f_1
iscar.singleton_class.singleton_class
. - The method-owner of
:f_2
iscar.singleton_class
.
The chain car
→ car.singleton_class
→ car.singleton_class.singleton_class
corresponds to the bottom row in the diagram at http://www.atalon.cz/rb-om/ruby-object-model/#sc-inheritance-sample.
Notes:
- The code does NOT create any new class (in particular, no anonymous class is created).
- In most Ruby programs, eigenclasses of eigenclasses are NOT made "actual" (see http://www.atalon.cz/rb-om/ruby-object-model/#actual-lists).