当前位置:网站首页>辨析 Ruby 中的 Method 与 Proc
辨析 Ruby 中的 Method 与 Proc
2022-07-26 15:44:00 【飞驰的西瓜】
Ruby is simple in appearance, but is very complex inside, just like our human body. — Matz https://www.ruby-lang.org/en/about
Ruby 与 Python、Scala 类似,在一切皆是对象(Seeing Everything as an Object)的基础上,支持函数式编程,这意味着函数是一等成员,可以作为参数传入,也可以作为函数值返回。
但是,Ruby 中的函数并没有其他动态语言中那么简单,它提供了 Method 与 Proc 两个类来表示函数的概念,对于这两个类的区别无论是官方文档还是 Stackoverflow 上的问题,解释的都非常模糊。在其他语言函数很习以为常的用法在 Ruby 中却行不通,就其原因还是不清楚这两个类的区别,希望这篇文章能够帮助大家理解好 Ruby 中的“函数”概念,做到深入浅出,与其他函数式语言融会贯通。
Block-oriented Programming
Ruby 中代码块最常见的形式既不是 Proc 也不是 Method,而是 block。比如:
# 遍历 Range/Array 等
(0..10).each do |num|
puts num
end
# 读取文件
File.foreach('README.md').with_index do |line, line_num|
puts "#{line_num}: #{line}"
end
# 遍历文件
Dir.glob('*.rb') {|ruby_src| puts "found #{ruby_src}"}上面示例演示了block的两种字面量(literal)形式,非常方便简洁。但有一点需要注意,block 仅仅是 Ruby 提供的一语法糖衣,并不把其赋值给某一变量。如果自定义函数需要调用传入的block,需要采用yield方式。
# 在 Array 类中添加自定义函数
class Array
def my_each
0.upto(size) do |i|
yield self[i]
end
end
end
%w(a b c).my_each do |item|
puts item
end面向函数式的 Proc
block 的优势是简洁,但是有个缺点就是无法复用,因为并不存在block类型。但在其他语言中,函数名可以随意传递,下面举一 Python 的例子:
def myinc(x):
return x + 1
map(myinc, [1,2,3]) # => [2, 3, 4]
map(myinc, [4,5,6]) # => [5, 6, 7]Ruby 中与其对应的是过程(Proc),与上面功能等价的 Ruby 代码为:
myinc = Proc.new {|num| num + 1}
# 或下面两种方式
# myinc = proc {|num| num + 1}
# myinc = lambda {|num| num + 1}
[1,2,3].map(&myinc)上面代码最关键的是&myinc中的&,由于 map 函数后面可以跟一个 block,所以需要把 Proc 转为 block。
当
&符号出现在函数参数列表中时,会把其后面的参数转为 Proc,并且把转化后的参数作为 block 传递给调用者。 http://stackoverflow.com/a/9429972/2163429
我这里有个更好的理解大家可以参考:
&在C语言中为取地址符,Ruby 中的函数参数后面可以跟一个 block,由于这个 block 不是参数的一部分,所以没有名字,这很理所当然可以把 block 理解为一内存地址,block_given?函数可以检查这个block是否存在。&myinc可以理解为取 Proc 的地址传给 map 函数。
[1,2,3].map(myinc)
# 这种写法会报下面的错误
# in `map': wrong number of arguments (given 1, expected 0) (ArgumentError)所以,Ruby 中的 Proc 和其他动态语言的函数是等价的,下面再举一例说明
def myfilter(arr, validator)
arr.each do |item|
if validator.call(item)
puts item
end
end
end
myfilter([1,2,3,4], lambda {|num| num > 3}) # 输出 4
# 此外, 还可以在定义 myfilter 时,利用 & 将最后的 block 转为 Proc
def myfilter(arr, &validator)
arr.each do |item|
if validator.call(item)
puts item
end
end
end
myfilter([1,2,3,4]) {|num| num > 3}
# 输出 4proc vs. lambda
上面介绍过,Proc 有两种字面量形式:
myinc = proc {|num| num + 1} # 与 Proc.new 等价
myinc = lambda {|num| num + 1}这两种形式的 Proc 有以下两点不同:
proc形式不限制参数个数;而lambda形式严格要求一致
proc中的return语句对调用方有效;而lambda仅仅对其本身起作用
面向对象的 Method
Ruby 中使用def定义的“函数”为Method类型,专为面向对象特性设计,面向对象更一般的说法是消息传递,通过给一对象发送不同消息,对象作出不同相应,这一点与 SICP 第三章的内容不谋而合。
class Rectangle
def initialize(width, height)
@width = width
@height = height
end
def area
@width * @height
end
end
rect = Rectangle.new 10, 20
# 传统方式
puts rect.area
# 消息传递方式
puts rect.send :area由于 Ruby 中方法名表示的是调用,所以一般可用与方法同名的 Symbol 来表示。
puts rect.method(:area)
#<Method: Rectangle#area>可以通过 Method 的 to_proc 方法可以将 Method 转为功能等价的 Proc。比如:
def myinc(num)
num + 1
end
[1,2,3].map(&method(:myinc))
# => [2,3,4]
# 在 Ruby 源文件的顶层定义的函数属于 Object 对象,所以上面的调用相当于:
# [1,2,3].map(&Object.method(:myinc))总结
block为 Proc 的语法糖衣,用于单次使用时Proc专为函数式编程设计,与其他动态语言的函数等价Method专为面向对象设计,消息传递的第一个参数
弄清 Method 与 Proc 的区别后,不得不欣赏 Ruby 语言设计的巧妙,兼具函数式与面向对象的精髓。实在是程序员必备利器。
参考
边栏推荐
- [five minute paper] reinforcement learning based on parameterized action space
- Teach the big model to skip the "useless" layer and improve the reasoning speed × 3. The performance remains unchanged, and the new method of Google MIT is popular
- Complete MySQL commands
- 什么是虚拟摄像头
- 第七章 在 REST 服务中支持 CORS
- OSPF综合实验
- 单例模式
- Interview with data center and Bi business (IV) -- look at the essence of ten questions
- VS2019Debug模式太卡进不去断点
- hawe螺旋插装式单向阀RK4
猜你喜欢

白话详解决策树模型之使用信息熵构建决策树

TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(2)

单例模式
![[leetcode] 33. Search rotation sort array](/img/da/e29dc6939803642e45f1ed48f664ce.png)
[leetcode] 33. Search rotation sort array

Refuse noise, the entry journey of earphone Xiaobai
“卡片笔记法”在思源的具体实践案例

Vs2019debug mode too laggy can't enter the breakpoint

parker泵PV140R1K1T1PMMC

基于SSM实现个性化健康饮食推荐系统

Understand │ XSS attack, SQL injection, CSRF attack, DDoS attack, DNS hijacking
随机推荐
线程和进程
13年资深开发者分享一年学习Rust经历:从必备书目到代码练习一网打尽
Jointly discuss the opening of public data, and the "digital document scheme" appeared at the digital China Construction Summit
八叉树建立地图并实现路径规划导航
Pytorch--- advanced chapter (function usage skills / precautions)
Chapter 7 supporting CORS in rest services
HaWe screw cartridge check valve RK4
数智转型,管理先行|JNPF全力打造“全生命周期管理”平台
kalibr标定realsenseD435i --多相机标定
2023 catering industry exhibition, China catering supply chain exhibition and Jiangxi catering Ingredients Exhibition were held in February
Daily1:SVM
Interview with data center and Bi business (IV) -- look at the essence of ten questions
Deep packet inspection using cuckoo filter paper summary
parker电磁阀D1VW020DNYPZ5
Reflection, enumeration, and lambda expressions
机器人手眼标定Ax=xB(eye to hand和eye in hand)及平面九点法标定
【EXPDP导出数据】expdp导出23行记录,且不包含lob字段的表,居然用时48分钟,请大家帮忙看看
TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(3)
换把人体工学椅,缓解久坐写代码的老腰吧~
TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(4)