6

我想像使用splat一样将参数传递给 Proc ,但它返回错误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

4

1 回答 1

7

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

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"
于 2015-07-18T21:01:16.587 回答