Friday, November 11, 2022

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

Issue

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?


Solution

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


Answered By - Jonne Haß
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.