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》是Python开发者学习和提升GUI编程技能的理想资料,无论你是初学者还是有一定经验的开发者,都可以从中获得宝贵的指导和灵感。通过深入学习这本书,你将能够熟练运用PySimpleGUI...
python-machine-learning-cookbook-preprocessing oreilly 英文 epub格式
标题“coverage-cookbook-complete-verification-academy”表明这是一本关于覆盖度(coverage)的食谱手册,隶属于Cadence Academy的官方文件。这种手册通常包含一系列经过精心设计的指导方案,旨在帮助读者理解和...
Bioinformatics-with-Python-Cookbook-Learn-how-to-use-modern-Python-bioinformatics-libraries-and-applications-to-do-cutting-edge-research-in-computational-biology.pdf
《CMake Cookbook》是关于构建、测试和打包模块化软件的专业指南,专注于现代CMake工具的使用。本书由Radovan Bast和Roberto Di Remigio合著,旨在帮助读者掌握CMake这一强大的跨平台构建系统。 CMake是一个开源的...
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 # 访问 ...
Lott -- Modern Python Cookbook -- 2016 -- code.7z
Aggarwal -- Flask Framework Cookbook -- 2014 -- code.7z
"NGINX Cookbook 高性能负载平衡高级配方" NGINX Cookbook 是一本专门介绍 NGINX 高性能负载平衡的书籍,书中涵盖了 NGINX 的高级配方和使用技巧,可以帮助读者快速搭建高性能的负载平衡系统。 GeoIP 模块和数据库...
Subramanian -- Python Data Science Cookbook -- 2015 -- code.7z