Ruby:是否可以在不对类名进行硬编码的情况下确定我的Ruby方法正
发布时间:2020-12-16 23:30:52 所属栏目:百科 来源:网络整理
导读:我是 Ruby的Nuby.我正在寻找一种方法来获取当前执行行的方法的包含Class对象.这可能没有硬编码类名吗? # hardcoded exampleclass A def to_s "I am a " + A.to_s # Class "A" is hardcoded here. Is there another way to reference the class A? endend 我
我是
Ruby的Nuby.我正在寻找一种方法来获取当前执行行的方法的包含Class对象.这可能没有硬编码类名吗?
# 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 我认为也许self.class可以工作,但是当类被子类化时它没有给我我想要的东西. # 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() 那么,是否存在允许访问包含类的关键字,方法或其他内容? 解决方法
试试这个
Class.nesting.first 这为您提供了方法的定义类. 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} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |