Proc对象相关

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值