Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Ruby:是否可以在不对类名进行硬编码的情况下确定我的Ruby方法正在执行的类?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 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}

大佬总结

以上是大佬教程为你收集整理的Ruby:是否可以在不对类名进行硬编码的情况下确定我的Ruby方法正在执行的类?全部内容,希望文章能够帮你解决Ruby:是否可以在不对类名进行硬编码的情况下确定我的Ruby方法正在执行的类?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。