gpt4 book ai didi

ruby - Ruby中如何获取给定单例(或本征)类对应的对象?

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

假设如下代码:

class A
end

a = A.new

As = class << a
self
end

# or:
# As = a.singleton_class

有什么方法可以从 As 得到 a 吗?

最佳答案

给你一个技巧:

class A
end

a = A.new

As = a.singleton_class

a2 = ObjectSpace.each_object.select{|obj| obj.singleton_class == As}.first

a2 == a # => true

关于ruby - Ruby中如何获取给定单例(或本征)类对应的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552394/

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