A Method object can be stored in a variable and passed as an argument to other methods. This is useful for passing preexisting methods into callbacks and listeners:
一个Method对象可以存储到变量中并作为参数传递给其他方法。这对于回调和监听器传递先前存在的方法非常有用。
A Method can also be used as a block:
一个Method对象可以存储到变量中并作为参数传递给其他方法。这对于回调和监听器传递先前存在的方法非常有用。
class EventSpawner
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
spawner = EventSpawner.new
spawner.subscribe do |old_state, new_state|
puts "Block triggered: state changed from #{old_state} to #{new_state}."
end
spawner.subscribe &EventListener.new.method(:hear)
spawner.change_state(4)
# Block triggered: state changed from 0 to 4.
# Method triggered: state changed from 0 to 4.
A Method can also be used as a block:
s = "sample string"
replacements = { "a" => "i", "tring" => "ubstitution" }
replacements.collect(&s.method(:gsub))
# => ["simple string", "sample substitution"]