`
orcl_zhang
  • 浏览: 243309 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

ruby cookbook -- 10.4Getting a Reference to a Method(获得方法引用)

    博客分类:
  • ruby
阅读更多
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对象可以存储到变量中并作为参数传递给其他方法。这对于回调和监听器传递先前存在的方法非常有用。
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"]

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics