ruby 未初始化的常量Array::Elem

6l7fqoea  于 2023-03-08  发布在  Ruby
关注(0)|答案(1)|浏览(148)

以下来自Sorbet常见问题解答的建议解决方案在执行期间导致uninitialized constant Array::Elembundle exec srb tc运行良好):

# typed: true

class Array
  extend T::Sig

  sig { returns(Elem) } # or T.nilable(Elem) unless you're confident this is never called on empty arrays
  def sample_one
    T.cast(sample, Elem)
  end

  sig { params(n: Integer).returns(T::Array[Elem]) }
  def sample_n(n)
    T.cast(sample(n), T::Array[Elem])
  end
end

我在一个Rails项目的config/initializers/monkeypatches/array.rb中添加了这个类。
我知道Require Elem when using Sorbet RBI,但是由于上面的解决方案来自官方的冰沙常见问题解答,我希望实际上有一种方法可以使它工作。

vmjh9lq9

vmjh9lq91#

FAQ指出,上面的类型是要写入RBI文件的内容,而不是Ruby源文件。
Ruby VM没有将stdlib类定义为Sorbet泛型--如果您希望对Array:
https://sorbet.org/docs/runtime#tsigwithoutruntimesig

相关问题