这是ruby的API文档中的解释:
Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.
Proc 对象是已绑定到一组局部变量的代码块。一旦绑定,代码可以被称为在不同的情况下,仍然访问这些变量。
本来块是可以放在方法的后面,然后在方法中用yidld字符来使用块的,同时这个yield也可以有参数。但是要在不同的方法中使用同一个代码块时可能就有点麻烦了,就需要每次调用方法时
就写一个代码块,这样就会照成相同的代码重复出现的情况(违背了don't repeat yourself的原则)。
这时我们就可以使用Proc这个类了,这个类把一个代码块先变成Proc对象,在分别放到不同的方法中去使用,这样就不会重复了,eg:
class Money
def my_method p
ten p
hundred p
thousand p
end
def ten p
p.call 10 #call是指执行压缩的proc对象
end
def hundred p
p.call 100
end
def thousand p
p.call 1000
end
end
p = Proc.new{ |x| puts x*10 }
money = Money.new
puts money.my_method p
#=>100
#=>1000
#=>10000</span>
1.Proc.new 是一种创建该对象的一种方式
2.to_proc 创建是把method对象转成proc对象的一种方式
eg:
a=:to_s.to_proc
a.call 23
这时把symbol对象化成Proc对象,如题则把to_s方法当成一个块化成Proc对象
3.&符号也可以把块变成Proc对象 eg:[1,2,3].collect(&:to_s)
=> ["1","2","3"]
4.lambda()也可以转化.