Proc对象定义:
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对象的3种方法:
①Proc.new 不要求参数匹配
②lambda 要求参数匹配
③proc 要求参数匹配
proc_new_obj = Proc.new {|a,b,c| p [a,b,c]}
proc_new_obj.call(1) # => [1, nil, nil]
proc_new_obj.call(1,2,3,4) # => [1, 2, 3]
lambda_obj = lambda{|a,b,c| p [a,b,c]}
lambda_obj.call(1) # => ArgumentError: wrong number of arguments (1 for 3)
lambda_obj.call(1,2,3,4) # => ArgumentError: wrong number of arguments (4 for 3)
lambda_obj.call(1,2,3) # => [1, 2, 3]
①②③都是返回程序对象
②③完全相同
除了不要求参数匹配以外,①和②③相同
调用Proc对象方法:
proc_obj.call
自定义方法中使用proc:
基本用法
1:
def foo(x, fn)
x ** 2 + fn.call()
end
x = 3
foo(5, lambda { x * 2 }) # => 31
2:
def foo(x, &fn)
x ** 2 + fn.call()
end
x = 3
foo(5) { x * 2 } # => 31
3:
def foo(x)
x ** 2 + yield
end
x = 3
foo(5) { x * 2 } # => 31
扩展用法
ruby和rails框架中经常用到第3种,或第2,3的结合
def foo(&block)
puts "foo"
foo1(&block)
end
def foo1
puts "foo1_step1"
yield
end
foo() {puts "foo1_main_step"}
# => foo
# => foo1_step1
# => foo1_main_step