gpt4 book ai didi

Ruby:是否可以在不对类名进行硬编码的情况下确定我的 Ruby 方法在其中执行的类?

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:00 27 4
gpt4 key购买 nike

我是 Ruby 的 Nuby。我正在寻找一种方法来获取当前执行行的方法的包含类对象。如果不对类名进行硬编码,这可能吗?

# 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#ancestors :

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

您将获得比您定义的更多的类,因此您需要在 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 可以是模块或类,所以如果你只想要类,你可以使用:

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 accessing the containing class?

我找不到一个。添加

puts method(__method__).owner

Animal#to_sMammal#to_s 仍然返回 Camel

关于Ruby:是否可以在不对类名进行硬编码的情况下确定我的 Ruby 方法在其中执行的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538065/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com