Question

I have two questions:

  1. Does method f_1 belong to the metaclass anonymous class?
  2. 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
Was it helpful?

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:

  1. f_1 is a class method on car's singleton class and can be called like this:

    car.singleton_class.f_1
    
  2. 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:

  1. The method-owner of :f_1 is car.singleton_class.singleton_class.
  2. The method-owner of :f_2 is car.singleton_class.

The chain carcar.singleton_classcar.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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top