創(chuàng)建Proc對(duì)象
- Proc.new
p = Proc.new { |m| m+1 }
p.call(3) #=> 4
- proc
p = proc { |m| m+ 1 }
p.call(3) #=>4
- lambda
la = lambda { |m| m + 1 }
la.class #=> Proc
la.call(3) # => 4
- ->
p = ->(m) { m + 1}
p.call(3) #=> 4
&,將代碼塊作為非匿名參數(shù)傳遞
def math(a,b)
yield(a,b)
end
def do_math(a,b,&operation)
math(a,b,&operation)
end
do_math(2,3) { |x,y| x + y} #=>5
- &操作符的含義
def my_method(&my_proc)
my_proc
end
p = my_method { |name| "Hello, #{name.capitalize}" }
p.call("getsuKami") # => Hello, GetsuKami
&操作符的含義是:這是一個(gè)Proc對(duì)象剩彬,我想把他當(dāng)成代碼塊來(lái)使用酷麦。最掉&操作符,就能再次得到一個(gè)Proc對(duì)象喉恋。
def my_method(name)
"#{name}, #{yield}"
end
my_proc = proc { "Hello" }
my_method("Bob", &my_proc) # => Bob,Hello
Proc與Lambda的對(duì)比
用Lambda創(chuàng)建的Proc叫l(wèi)ambda贴铜,用其他方式創(chuàng)建的Proc稱為proc。
可以使用Proc#lambda?來(lái)檢測(cè)Proc是不是lambda
使用->
方法創(chuàng)建之后: p.lambda? 返回為T(mén)rue
- proc 與lambda 瀑晒,return的區(qū)別
proc 會(huì)從定義proc的作用域中返回绍坝,而lambda只是從lambda中返回。
def double(my_lambda)
my_lambda.call * 2
end
def an_double
p = Proc.new { return 10 } √υ谩#在這定義
result = p.call #在這里程序就被返回轩褐,就是從an_double的作用域返回
return result * 2 #
end
def ann_double(my_proc)
my_proc.call * 2
end
la = lambda { return 10 }
double(la) #=>20
an_double #=> 10
p = Proc.new { return 10 } #定義在main中
# ann_double(p) #=> error,不能main里面返回
- 參數(shù)
lambda會(huì)嚴(yán)格檢查參數(shù)。
proc不會(huì)玖详,如果多了把介,就忽略后面多的,如果少了蟋座,就用nil代替拗踢。
yield and self
yield 對(duì)代碼塊的調(diào)用
self 對(duì)當(dāng)前對(duì)象的引用
class A
def hello1
yield self if block_given?
end
def hello2
yield 1 if block_given?
end
def self.hello
yield self if block_given?
end
end
A.new.hello1 { |var| p var} #=>#<A:0x0000000147eef0>
A.new.hello2 { |var| p var} # => 1
A.hello { |var| p var } # => A
self 就是作為一個(gè)參數(shù)傳遞進(jìn)去而已。