sorbet

Sorbet sig for anonymous forwarded blocks


Ruby 3.1 added anonymous block forwarding, so you can do:

def do_something(&)
  stuff.each(&)
end

Rubocop added a default rule that encourages this style, so I started looking into implementing this, but I can't figure out whether it's possible to specify a sig for anonymous blocks or not. If Sorbet doesn't support this, it'd be nice if this were mentioned explicitly in the docs or flagged as unsupported by the type checker. I see from here that implicit yield blocks can't be typed, but there's no mention of explicit blocks that are unnamed.

Here's a Sorbet.run link with some attempts that didn't work: sig { params(:& => T.proc) } and sig { params("&": T.proc) } don't seem to work, with "Malformed sig. Type not specified for argument &" and "Unknown argument name &" errors, in addition to a "found NilClass for block argument" error.


Solution

  • As you've noticed, Sorbet's sig syntax relies on referring to the name of an explicit block parameter, which anonymous block parameters don't have, by definition.

    This isn't currently possible today, nor is having an implicit block (that can only be called with yield). I've opened a github issue to request this feature:

    https://github.com/sorbet/sorbet/issues/6832