Assign method pointer to another method
class MyEntity
def initialize
@listeners = []
@state = 0
end
def subscribe(&listener)
@listeners << listener
end
def change_state(new_state)
@listeners.each { |l| l.call(@state, new_state) }
@state = new_state
end
end
class EventListener
def hear(old_state, new_state)
puts "Method triggered: state changed from #{old_state} " +
"to #{new_state}."
end
end
myObject = MyEntity.new
myObject.subscribe do |old_state, new_state|
puts "Block triggered: state changed from #{old_state} to #{new_state}."
end
myObject.subscribe &EventListener.new.method(:hear)
myObject.change_state(4)
Related examples in the same category