Define unique blocks

I have an array to which I continue to add blocks of code at different points in time. When a specific event occurs, the iterator iterates through this array and gives the blocks one by one.

Many of these blocks are the same, and I want to avoid repeating blocks.

This is a sample code:

    @after_event_hooks = []

    def add_after_event_hook(&block)
      @after_event_hooks << block
    end

Something like @after_event_hooks.uniqor @after_event_hooks |= blocknot working.

Is there a way to compare blocks or check their uniqueness?

+4
source share
3 answers

Blocks cannot be tested for uniqueness, since this will mean that they represent the same functions, which is impossible, and has long been studied in the field of computer science.


, , Ruby ", , .

, , , . , , , .

+2

@hakcho, . API , :

@after_event_hooks = {}

def add_after_event_hook(name, &block)
  @after_event_hooks[name] = block
end

def after_event_hooks
  @after_event_hooks.values
end
0

, - :

class AfterEvents
  attr_reader :hooks

  def initialize
    @hooks = {}
  end

  def method_missing(hook_sym, &block)
    @hooks[hook_sym] = block
  end
end

:

events = AfterEvents.new
events.foo { puts "Event Foo" }
events.bar { puts "Event Bar" }

# test
process = {:first => [:foo], :sec => [:bar], :all => [:foo, :bar]}

process.each { |event_sym, event_codes|
  puts "Processing event #{event_sym}"
  event_codes.each { |code| events.hooks[code].call }
}
# results:
# Processing event first
# Event Foo
# Processing event sec
# Event Bar
# Processing event all
# Event Foo
# Event Bar
0

All Articles