惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Threat Research - Cisco Blogs
Latest news
Latest news
Project Zero
Project Zero
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google DeepMind News
Google DeepMind News
P
Privacy & Cybersecurity Law Blog
T
Troy Hunt's Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AWS News Blog
AWS News Blog
Hacker News: Ask HN
Hacker News: Ask HN
S
Security @ Cisco Blogs
C
Cisco Blogs
Help Net Security
Help Net Security
I
Intezer
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
腾讯CDC
S
Secure Thoughts
MyScale Blog
MyScale Blog
Recorded Future
Recorded Future
G
GRAHAM CLULEY
L
LINUX DO - 热门话题
A
About on SuperTechFans
C
CXSECURITY Database RSS Feed - CXSecurity.com
IT之家
IT之家
J
Java Code Geeks
The Hacker News
The Hacker News
阮一峰的网络日志
阮一峰的网络日志
Scott Helme
Scott Helme
Recent Announcements
Recent Announcements
AI
AI
Cisco Talos Blog
Cisco Talos Blog
B
Blog RSS Feed
V
Vulnerabilities – Threatpost
C
Check Point Blog
Security Latest
Security Latest
S
SegmentFault 最新的问题
T
The Exploit Database - CXSecurity.com
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
M
MIT News - Artificial intelligence
T
The Blog of Author Tim Ferriss
Attack and Defense Labs
Attack and Defense Labs
PCI Perspectives
PCI Perspectives
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research

博客园 - sizzle

软件单元测试之我见 非空判断 在COM中使用数组参数-SafeArray[转载] 指针赋值 - sizzle - 博客园 进程的深度隐藏 文件隐藏 Windows下网络数据报的监听和拦截技术 三键屏蔽 键盘知识 如何获取当前程序文件的路径 Net Remoting[转自Bruce Zhang's Blog] 解码 XML 和 DTD 【读书笔记】[Effective C++第3版][第27条]尽量不要使用类型转换 P2P之UDP穿透NAT的原理与实现 CommandBinding用法 窗体显示中Form.Show()和Form.ShowDialog()的区别 一段高深代码--未解 使用C#注销/关闭计算机 TEA加密算法的C/C++实现
ruby函数回调的实现方法
sizzle · 2016-01-15 · via 博客园 - sizzle

以前一直困惑ruby不像python,c可以将函数随意传递,然后在需要的时候才去执行。其实本质原因是ruby的函数不是对象。

通过查阅资料发现可以使用如下方法:

def func(a, b)
  puts a + b
end

f = method(:func)
f.call(1, 2)

上面是使用Method对象封装函数,然后就可以通过操作该Method对象实现函数的参数传递。

曾经一度认为上面方法才是将函数作为参数使用的正统方法,后来才发现原来是我太执着于c的函数指针的使用模式里,而没有真正体会到ruby block的精髓,使用block的实现方法:

def func(a, b)
  puts a + b
end

def use_func(a, b)
  yield a, b
end

use_func(1, 2) do |a, b|
  func a, b
end

说明一下用意:

将函数作为参数传递给其他对象,其实根本目的是让其他对象可以使用该函数,使用方法就如同use_func的实现,这时关心的内容其实仅仅是参数列表和返回值,也就是说我们可以使用block将func的“形”传递给use_func,而在真正需要使用func的时候再在block中执行func即可。

当然,举例的func实现过于简单,大家可能觉得只需要将puts语句放在block中即可,但是当实现内容增多或者需要重用时,func还是有存在的必要。