Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous classes in Ruby

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
like image 749
user413881 Avatar asked Jul 19 '26 02:07

user413881


1 Answers

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
    
like image 97
Rob Davis Avatar answered Jul 21 '26 23:07

Rob Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!