Ruby: Is it possible to define a class that my Ruby method executes without hard coding the class name?

I am Nubi Ruby. I am looking for a way to get the containing class object of a method of the current execution string. Is this possible without hard coding the class name?

# hardcoded example class A def to_s "I am a " + A.to_s # Class "A" is hardcoded here. Is there another way to reference the class A? end end 

I thought that maybe self.class would work, but it did not give me what I was looking for when a class of subclasses.

 # Following Outputs=> I am a Camel I am a Camel I am a Camel # but I want => I am a Camel I am a Mammal I am a Animal class Animal def to_s "I am a " + self.class.to_s end end class Mammal < Animal def to_s "I am a " + self.class.to_s + " " + super end end class Camel < Mammal def to_s "I am a " + self.class.to_s + " " + super end end puts Camel.new() 

So, is there a keyword, method, or something that allows you to access the contained class?

+6
source share
2 answers

try it

 Class.nesting.first 

This gives you the defining class of the method.

 class A def example { defining_class: Class.nesting.first, self_class: self.class } end end class B < A end B.new.example # => {:defining_class=>A, :self_class=>B} 
+3
source

You will need Class#ancestors :

 Camel.ancestors #=> [Camel, Mammal, Animal, Object, Kernel, BasicObject] 

You will get more classes than you defined, so you need to stop at Object :

 class Animal def to_s "I am a " + self.class.ancestors.take_while{|klass| klass != Object}.join(' and a ') end end class Mammal < Animal end class Camel < Mammal end puts Animal.new # => I am a Animal puts Mammal.new # => I am a Mammal and a Animal puts Camel.new # => I am a Camel and a Mammal and a Animal 

ancestors can be modules or classes, so if you just want Classes, you can use:

 def to_s "I am a " + self.class.ancestors.take_while{|klass| klass < Object}.join(' and a ') end 

So, is there a keyword, method, or something that allows you to access the containing class?

I could not find him. Adding

 puts method(__method__).owner 

until Animal#to_s or Mammal#to_s still returns Camel .

+5
source

Source: https://habr.com/ru/post/1013888/


All Articles