Ruby中,所謂帶塊(block)的方法是指對控制結構的抽象,最初設計是用於對迴圈進行抽象,所以又稱迭代器。
文法:method_name do...end 或 method_name {}
1#塊調用
2def foo
3 print yield(5)
4end
5
6foo {|a|
7 if a > 0
8 "positive"
9 elsif a < 0
10 "negative"
11 else
12 "zero"
13 end
14}
15
16foo()
17
18#使用了proc(過程對象)的塊調用
19quux = proc {|a|
20 if a > 0
21 "positive"
22 elsif a < 0
23 "negative"
24 else
25 "zero"
26 end
27}
28
29def foo(p)
30 print p.call(5)
31end
32
33foo(quux)
1//傳統委託
2public delegate string fooDelegate(int a);
3public string foo(int a)
4{
5 if(a > 0)
6 return "positive";
7 else if(a < 0)
8 return "negative";
9 return "zero";
10}
11fooDelegate myD1 = new fooDelegate(foo);
12Console.WriteLine(myD1(5));
13
14//匿名委託
15public delegate string fooDelegate(int a);
16fooDelegate myD1 = delegate(int a)
17{
18 if(a > 0)
19 return "positive";
20 else if(a < 0)
21 return "negative";
22 return "zero";
23}
24Console.WriteLine(myD1(5));