Method with splat arguments, which captures a block which takes the same number of arguments

Hi there,

Is there a clever way of doing something like this?

def foo(*args, &block : typeof(args) ->)
  block.call(args)
end

puts foo(1, 2, 3) { |a,b,c| a+b+c }

I need to specify the type of the block before I can capture it, but the compiler tells me I can’t call typeof here, and because I don’t know how many items the typle args contains I don’t know what type the block should be, although if I understand correctly, then at this point the compiler does know.

The following works, but doesn’t allow me to capture the block of course:

def foo(*args, &)
  yield args
end

puts foo(1, 2, 3) { |a,b,c| a+b+c }

You have to use a splat restriction and specify the return type:

def foo(*args : *T, &block : *T -> U) forall T, U
  block.call(*args)
end

puts foo(1, 2, 3) { |a,b,c| a+b+c } # => 6
3 Likes

Excellent, thank you, that is exactly what I needed!