Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Procs with variable arguments in Crystal?

Tags:

crystal-lang

I want to pass arguments to a Proc like using splat, but it returns an error 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

like image 518
Hugo Abonizio Avatar asked Jul 18 '15 20:07

Hugo Abonizio


1 Answers

You need to specify the argument list everywhere.

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"
like image 65
Jonne Haß Avatar answered Sep 22 '22 17:09

Jonne Haß