# Hash with Block/Proc

**URL:** <https://forum.crystal-lang.org/t/hash-with-block-proc/1195>\
**Category:** Help & Support\
**Created:** [October 2, 2019, 11:40pm UTC](https://forum.crystal-lang.org/t/hash-with-block-proc/1195 "2019-10-02T23:40:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![valenciaj](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/valenciaj/32/1446_2.png) [@valenciaj](https://forum.crystal-lang.org/u/valenciaj)\
**Post date:** [October 2, 2019, 11:40pm UTC](https://forum.crystal-lang.org/t/hash-with-block-proc/1195/1 "2019-10-02T23:40:33Z")

</div>

How to define `???` type on below code:

```crystal
class Events
  alias EventHandlers = Hash(String, Array(???))

  @handlers : EventHandlers

  def initialize
    @handlers = EventHandlers.new
  end

  def add_handler(name, &block)
    unless @handlers[name]?
      @handlers[name] = Array(???).new
    end

    @handlers[name] << block
  end

  def fire_event(name, payload)
    if handlers = @handlers[name]?
      handlers.map(&.call(payload))
    end
  end
end

```

Using previous code

```crystal
events = Events.new

events.add_handler("custom_event") do |payload|
  puts payload.inspect
end

event.fire_event("custom_event", payload: { foo: :bar })

```

If it’s `Proc`, I must specify types like [`Proc(*T, R)`](https://crystal-lang.org/api/0.31.1/Proc.html#call(*args:*T):R-instance-method), but I don’t want to care about `Proc` what’s returning, sometimes `String`, `Int32`, `Nil` or anythingelse.

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [October 3, 2019, 12:04am UTC](https://forum.crystal-lang.org/t/hash-with-block-proc/1195/2 "2019-10-03T00:04:12Z")

</div>

It would most likely have to be a proc, could always just set the return type as `Nil`, pretty sure that would cause the proc to return `nil` even if its not the return value.

The bigger challenge will be the variable payload.

---

<div class="post-metadata">

**Author:** ![stronny](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/stronny/32/228_2.png) [@stronny](https://forum.crystal-lang.org/u/stronny)\
**Post date:** [October 3, 2019, 11:27am UTC](https://forum.crystal-lang.org/t/hash-with-block-proc/1195/3 "2019-10-03T11:27:52Z")

</div>

Coming from Ruby that feels natural, however in my experience it’s better not to sidestep the static analysis. If you really need an arbitrary payload, you may do what `JSON::Any` does using recursive aliases, which still restricts the types by the way, or you may forego this aspect of your program and for example start building types of Event, then just use the parent as the type restriction. Or a module, that should also work.
