10

I am trying to get the name of the class from within a static method within the class:

class A
  def self.get_class_name
    self.class.name.underscore.capitalize.constantize
  end
end

Though this returns Class instead of A. Any thoughts on how do I get A instead?

Eventually I also want to have a class B that inherits from A that will use the same method and will return B when called.

The reason I am doing this is because I have another object under this domain eventually: A::SomeOtherClass which I want to use using the result I receive.

6
  • 1
    Is the method supposed to return a string, i.e. "A"? Commented Jul 6, 2015 at 13:23
  • @Stefan, I think he was just trying to understand how to get the current class name inside a class method. This is probably just an example. Commented Jul 6, 2015 at 13:25
  • Do you want the class A or the name (string) "A"? Commented Jul 6, 2015 at 13:46
  • What is constantize in Ruby? Commented Jul 6, 2015 at 13:46
  • 2
    @DanBenjamin from within class methods, self returns the class object and name returns the class name. Commented Jul 6, 2015 at 15:42

2 Answers 2

15

Remove .class:

class A
  def self.get_class_name
    self.name.underscore.capitalize.constantize
  end
end

self in a context of a class (rather than the context of an instance method) refers to the class itself.

This is why you write def self.get_class_name to define a class method. This means add method get_class_name to self (aka A). It is equivalent to def A.get_class_method.

It is also why when you tried self.class.name you got Class - the Object#class of A is Class.

To make this clearer, consider the output of:

class A
  puts "Outside: #{self}"

  def self.some_class_method
    puts "Inside class method: #{self}"
  end

  def some_instance_method
    puts "Inside instance method: #{self}"
  end
end

A.some_class_method
A.new.some_instance_method

Which is:

Outside: A
Inside class method: A
Inside instance method: #<A:0x218c8b0>
Sign up to request clarification or add additional context in comments.

Comments

0

The output for this:

class NiceClass
  def self.my_class_method
    puts "This is my #{name}"
  end
end

NiceClass.my_class_method

Will be:

This is my NiceClass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.