Search code examples
crystal-lang

Call block with call not work


I try to use code from this issue

def call(&block)
  block.call(3, "test")
end

call do |x, y|
  puts x
  {x, y}
end

But only get error:

wrong number of block arguments (given 2, expected 0)

Is it ok, maybe there is some other way to call block?

Playground link: https://play.crystal-lang.org/#/r/4t8h

Github issue: https://github.com/crystal-lang/crystal/issues/6597


Solution

  • You can use either of these two forms:

    def call(&block : Int32, String -> {Int32, String})
      block.call(3, "test")
    end
    
    result = call do |x, y|
      {x, y}
    end
    
    result # => {3, "test"}
    

    or

    def call
      yield 3, "test"
    end
    
    result = call do |x, y|
      {x, y}
    end
    
    result # => {3, "test"}
    

    And some additional info can be found here.