Ian B. Ian B. - 7 months ago 10
Ruby Question

How to output the Ruby class name wrapped around Singleton method

Thanks for reading-

I am unable to find a way to display the name of the class which holds a Singleton method. I have tried a number of different stabs and standard library searches but haven't found an answer. An easy way to explain my goal would be:

class Bermuda
class << self
def grass
puts self.superclass.name
end
end
end

# my goal is that this expression
Bermuda.grass

# will output a string of the class name it resides in
=> "Bermuda"


I understand this is partially pointless, because why would you need a class method to display the information that you would need in the first place to call that method? I'm not sure just curious if it's possible or I'm completely missing the scope here. Thanks!

Answer

Just call name on self

class Bermuda
  class << self
    def grass
      puts self.name
    end
  end
end