Ruby编程:特性、应用与探索
1. 块与Proc
在Ruby中,块和Proc是非常重要的概念。Proc对额外参数的处理与lambda有所不同。例如:
# Extra args are no problem for procs
plusTwo.call(100, 200, 300)
# ...but they are a problem for lambdas
begin
plusFour.call(100, 200, 300)
rescue ArgumentError
puts 'Rescued'
# Message will be output
end
这里, plusTwo 作为Proc可以处理额外参数,而 plusFour 作为lambda则会抛出 ArgumentError 异常。
同时,我们可以使用 map 方法结合Proc对数组元素进行处理:
a = [10, 20, 30, 40, 50]
p a.map(&plusTwo)
# All passed the same way
p a.map(&plusThree)
p a.map(&plusFour)
p a.map(&plusFive)
p a.map(&(->(x) {x * 10}))
# anonymous procs!
p a.map &->(
超级会员免费看
订阅专栏 解锁全文
45

被折叠的 条评论
为什么被折叠?



