如何在Crystal中创建具有可变参数的Proc?

我想将参数传递给Proc,如使用splat,但它返回错误 wrong number of block arguments (1 for 0)

$callbacks = {} of String => Array(->)

def add_callback(event, &block)
  begin
    $callbacks[event.to_s] << block
  rescue
    $callbacks[event.to_s] = [block]
  end
end

add_callback(:event) do |arg|
  puts "event!"
end

$callbacks["event"].first.call

Error in line 11: wrong number of block arguments (1 for 0) http://carc.in/#/r/7gw

回答(1)

2 years ago

您需要在任何地方指定参数列表 .

class EventManager
  def initialize
    @callbacks = Hash(String, Array(String ->)).new {|h, k| h[k] = [] of String -> }
  end

  def add(event, &callback : String ->)
    @callbacks[event] << callback
  end

  def fire(event, argument : String)
    @callbacks[event].each &.call(argument)
  end
end

callbacks = EventManager.new
callbacks.add("foo") do |argument|
  puts "Got #{argument}"
end
callbacks.add("bar") do
  puts "I was called"
end
callbacks.fire "foo", "Ping"
callbacks.fire "bar", "Pong"