uninitialized constant Array::Elem

115 Views Asked by At

The following recommended solution from the Sorbet FAQ results in uninitialized constant Array::Elem during execution (bundle exec srb tc runs fine):

# 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

I added this class to config/initializers/monkeypatches/array.rb in a Rails project.

I'm aware of Require Elem when using Sorbet RBI, but since the above solution is from the official Sorbet FAQ, I'm hoping there actually is a way to make it work.

1

There are 1 best solutions below

1
jez On

The FAQ says that the above type is what to write in an RBI file, not a Ruby source file.

The Ruby VM does not define stdlib classes as Sorbet generics—you will have to use T::Sig::WithoutRuntime if you wish to monkey patch Array:

https://sorbet.org/docs/runtime#tsigwithoutruntimesig