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"]
分享到:
相关推荐
PySimpleGUI cookbook-zh-CN 中文版 非机器翻译(目录标题未翻译)
Boost C++ Application Development Cookbook - Second Edition
coverage-cookbook-complete-verification-academy Candence Academy官方coverage文档
python-machine-learning-cookbook-preprocessing oreilly 英文 epub格式
Modern-CPP-Programming-Cookbook-Second-Edition-master Packt 出版 仅供学习参考,阅后删除。
Bioinformatics-with-Python-Cookbook-Learn-how-to-use-modern-Python-bioinformatics-libraries-and-applications-to-do-cutting-edge-research-in-computational-biology.pdf
nginx-cookbook-recipes-high-performance
网上很难找的一本书,思科的资深CCIE写的。 The Network Design Cookbook ... This book will be a valuable tool in both learning how to design a network, as well as a reference as you advance in your career.
Linux Shell Scripting Cookbook - Third Edition by Clif Flynt English | 29 May 2017 | ASIN: B01N80F75Z | 552 Pages | AZW3 | 1.36 MB Do amazing things with the shell About This Book Become an expert ...
Programming ArcGIS with Python Cookbook - Second Edition, mobi格式
Programming ArcGIS with Python Cookbook - Second Edition,epub格式
Unity Game Development Cookbook - Paris Buttfield-AddisonUnity Game Development Cookbook - Paris Buttfield-Addison
docker run -tid -p <port>:80 apachecn0/pandas-cookbook-code-notes # 访问 http://localhost:{port} 查看文档 PYPI pip install pandas-cookbook-code-notes pandas-cookbook-code-notes # 访问 ...
uvm-cookbook-registers-guide-verification-academy
NumPy-Cookbook-2nd-Edition-Over-90-fascinating-recipes-to-learn-and-perform-mathematical-scientific-and-engineering-Python-computations-with-NumPy.pdf
modern-cpp-programming-cookbook-2nd
IPython-Interactive-Computing-and-Visualization-Cookbook-Over-100-hands-on-recipes-to-sharpen-your-skills-in-high-performance-numerical-computing-and-data-science-with-Python.pdf
KVM实操手册, 英语简练易懂, 讲的面比较全, KVM的相关内容基本都涉及到了, 内容全面,可操作性强.