Assign method pointer to another method : Method Pointer « Method « Ruby






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

1.Use method from String class to map a method from String to a method pointer
2.Call String.instance_method to get a method pointer
3.Get pointer to a method in Fixnum