radha
radha

Reputation: 23

How to declare a block argument with one or two arguments in crystal

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?

Upvotes: 1

Views: 146

Answers (1)

Jonne Haß
Jonne Haß

Reputation: 4857

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

Upvotes: 2

Related Questions