Ruby 1.9概要(4) Block和Proc

1、Proc加了新方法Proc#yield ,这只是Proc#call的别名方法,是为了能让Proc也可以像block那样传入方法并且调用yield。

a_proc  =  Proc.new { | a,b |  a + b}
a_proc.
yield ( 1 , 2 #  => 3

def  test( & block)
  block.
yield ( 1 , 2 , 3 )
end
test do 
| a,b |
   a
+ b    #  => 3
end
test 
& a_proc  #  =>3


2、没有参数的block的基数 (参数个数,arity):
1.8

lambda {}.arity   # => -1

1.9

lambda {}.arity  # => 0

所谓arity就是方法调用无法忽略的参数个数。这跟Erlang,Prolog中的arity的概念并无二致。

3、proc关键字现在是Proc.new的同义词 ,proc在1.8的时候跟lambda关键字是同义词,也就是proc定义的是一个lambda而非字面

意义上的Proc,1.9改过来了。
1.9:


proc{
| a,b | }.arity         #  => 2
proc{ | a,b | }.call( 1 )         #  => nil
Proc.new{ | a,b | }.arity         #  => 2
Proc.new{ | a,b | }.call( 1 )         #  = nil


1.8:

proc{ | a,b | }.arity         #  => 2
proc{ | a,b | }.call( 1 )         #  => ERROR: (eval):1: wrong number of arguments (1 for 2)
Proc.new{ | a,b | }.arity         #  => 2
Proc.new{ | a,b | }.call( 1 )         #  => nil


1.8时候第二个调用出错的原因在于lambda在调用参数过多过少的时候都将报error,这是lambda跟Proc的一个区别之一。

4、Proc#lambda? 用来判断某个Proc是否具有lambda语义或者block语义:

lambda {}. lambda ?   # =>true
proc{}. lambda #  =>false
Proc.new{}. lambda #  =>false



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值