gpt4 book ai didi

ruby - 如何从混合模块调用 `self.class`?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:19 24 4
gpt4 key购买 nike

我有一个模块要包含在其他类中。它使用 Object#class方法,像这样:( sorbet.run link )

# typed: true
module M
def foo
self.class
end
end

对此,Sorbet 说

editor.rb:4: Method class does not exist on M https://srb.help/7003
4 | self.class
^^^^^^^^^^
Did you mean to `include Object` in this module?
???: Did you mean: Object#class?

现在它变得有趣了。 Error reference for 7003确实描述了这可以防止模块中包含在 BasicObject 中的类型错误。很好,所以我包括对象,正如检查员告诉我的那样:( sorbet.run link )

# typed: true
module M
include Object
def foo
self.class
end
end

错误消息毫无帮助,链接page #5032不存在。

editor.rb:2: Only modules can be included. This module or class includes Object https://srb.help/5032
2 |module M
^^^^^^^^

我花了一段时间才意识到它试图告诉我不能包含作为模块子类的类。与Ruby的报错信息对比:

$ ruby -e 'module M; include Object; end'
Traceback (most recent call last):
2: from -e:1:in `<main>'
1: from -e:1:in `<module:M>'
-e:1:in `include': wrong argument type Class (expected Module) (TypeError)

如何让我的代码通过 typed: true 级别?

最佳答案

这实际上是两个错误!感谢您指出它们:

class 不在我们 Kernel 的 shim 中:https://github.com/sorbet/sorbet/pull/1050我们永远不应该建议包含不是 Module 的东西:https://github.com/sorbet/sorbet/pull/1047

关于ruby - 如何从混合模块调用 `self.class`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56758793/

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