1

I want to be able accept a block argument, which takes one or two Int arguments

This code does not work, but expresses my intent.
def initialize(*input, &block : (Int32 | (Int32, Int32)) -> Int32) @input = input @calc = block end

This works for a block with one Int argument. How do I make it work with one or two Int arguments?

1 Answer 1

2

Taking a block parameter is optional in Crystal. So just declare the the block with the maximum number of arguments and decide on the call side how many of those you're going to take:

def foo(&block : (Int32, Int32) -> Int32)
  block.call(1, 2)
end

foo {|a, b| a + b } # => 3
foo {|a| a } # => 1
foo { 5 } # => 5

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.