Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class name from within the initialize method when class inherited from Hash

I have a class that inherits from Hash. When this class itself gets inherited from, I want to know the class name of the inheriting class from within the initialize method. When I call self I get {}, which doesn't know of the name method.

class Foo < Hash
  def initialize
    # Here i want to know that the class is Foo
  end
end

How do I get the class name?

like image 990
rausch Avatar asked Dec 11 '25 16:12

rausch


2 Answers

It’s very simple: self.class.name

like image 168
Daniel Brockman Avatar answered Dec 14 '25 09:12

Daniel Brockman


Daniel Brockman's answer will return you the string if you want to do a check:

if self.kind_of?(Foo)
  #whatever you want
end

The thing is due to the intent of the initializer, when you call Foo.new the instance will always be an instance of the class Foo or child, so I'm confused about what you're trying to do.

like image 43
danpickett Avatar answered Dec 14 '25 08:12

danpickett