gpt4 book ai didi

ruby - 为什么 Ruby 模块包含排除了模块的单例类?

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:57 25 4
gpt4 key购买 nike

当在 Ruby 中继承类时,单例类也会被继承:

class A
def self.hello
puts "hello"
end
end

class B < A
end

B.hello #=> "hello"

然而对于模块,情况并非如此:

module M
def self.goodbye
puts "goodbye"
end
end

class A
include M
end

A.goodbye #=> NameError

为了绕过这个限制,许多人诉诸于这个丑陋的 hack:

module M
def self.included(c)
c.extend ClassMethods
end

module ClassMethods
def goodbye
puts "goodbye"
end
end
end

好的,那么我的问题是:这种模块限制背后是否有理论/概念上的原因?还是只是实现困难?

在查看 C 源代码 (YARV/MRI) 后,我可以确定存在实现困难(并非不可克服,但都是一样的),但这是唯一的原因吗?这种限制还有其他原因吗?

谢谢

最佳答案

除非有人能提出令人信服的论据,否则我认为限制只是在于实现难度。尽管如此,我最近几天一直在研究这个问题,并且有一个新版本的 include 称为 include_complete ,它解决了这些困难并允许模块继承像类继承一样工作(带来在单例中)

在这里查看项目:http://github.com/banister/include_complete

请注意该项目仍处于测试阶段,但到目前为止似乎仍能按预期工作

关于ruby - 为什么 Ruby 模块包含排除了模块的单例类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3848552/

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