Ruby/Method/Method Pointer

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

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)



Call String.instance_method to get a method pointer

umeth = String.instance_method(:length)
m1 = umeth.bind("cat")
m1.call                         # 3
m2 = umeth.bind("caterpillar")
m2.call                         # 11



Get pointer to a method in Fixnum

unbound_plus = Fixnum.instance_method("+")
plus_2 = unbound_plus.bind(2)   # Bind the method to the object 2
sum = plus_2.call(2)    # => 4
plus_3 = plus_2.unbind.bind(3)



Use method from String class to map a method from String to a method pointer

str = "cat"
meth = str.method(:length)
a = meth.call               #  3  (length of "cat")
str << "erpillar"
b = meth.call               # 11  (length of "caterpillar")
str = "dog"
c = meth.call               # 11  (length of "caterpillar")