創建Proc對象
- 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
&,將代碼塊作為非匿名參數傳遞
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
&操作符的含義是:這是一個Proc對象,我想把他當成代碼塊來使用。最掉&操作符,就能再次得到一個Proc對象。
def my_method(name)
"#{name}, #{yield}"
end
my_proc = proc { "Hello" }
my_method("Bob", &my_proc) # => Bob,Hello
Proc與Lambda的對比
用Lambda創建的Proc叫lambda,用其他方式創建的Proc稱為proc。
可以使用Proc#lambda?來檢測Proc是不是lambda
使用->
方法創建之后: p.lambda? 返回為True
- proc 與lambda ,return的區別
proc 會從定義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里面返回
- 參數
lambda會嚴格檢查參數。
proc不會,如果多了,就忽略后面多的,如果少了,就用nil代替。
yield and self
yield 對代碼塊的調用
self 對當前對象的引用
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 就是作為一個參數傳遞進去而已。