CodeOverload
CodeOverload

Reputation: 48475

Get extended class's name

Given the following:

class Animal
  def self.info
    "This is the class '#{self.class.to_s}', and the available breeds are #{BREEDS.to_s}"
  end
end

class Dog < Animal
  BREEDS = %w(x y z)
end

When i call:

Dog.info
=> This is the class 'Class'

I'm expecting Dog instead of Class, how can i get the current class name from Animal without putting info in the Dog class.

Also, i get undefined constant Animal::BREEDS

What am i missing?

Upvotes: 0

Views: 49

Answers (1)

Zabba
Zabba

Reputation: 65467

self.to_s, not self.class.to_s. You are already "inside" self in Animal

To access the constant: self::BREEDS

So:

class Animal
  def self.info
    "This is the class '#{self.to_s}', and the available breeds are #{self::BREEDS.to_s}"
  end
end

Upvotes: 2

Related Questions