|
|
||
------------------------------------------------------------ Class: 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. def gen_times(factor) return Proc.new {|n| n*factor } end times3 = gen_times(3) times5 = gen_times(5) times3.call(12) #=> 36 times5.call(5) #=> 25 times3.call(times5.call(4)) #=> 60 ------------------------------------------------------------------------ Class methods: -------------- new Instance methods: ----------------- ==, [], arity, binding, call, clone, dup, to_proc, to_s
==== Proc ==== Proc はブロックをコンテキスト(ローカル変数のスコープやスタックフ レーム)とともにオブジェクト化した手続きオブジェクトです。Proc は ローカル変数のスコープを導入しないことを除いて名前のない関数のように使 えます(ダイナミックローカル変数は Proc ローカル の変数として使えます)。 Proc がローカル変数のスコープを保持していることは以下の例で 変数 var を参照できていることからわかります。 var = 1 $foo = Proc.new { var } var = 2 def foo $foo.call end p foo # => 2 Proc を生成したメソッドからリターンしてしまった後は Proc からの return, retry は例外 LocalJumpError を発生させます。 def foo proc { return } end foo.call # => in `call': return from proc-closure (LocalJumpError) def foo proc { retry } end foo.call # => in `call': retry from proc-closure (LocalJumpError) イテレータに対して Proc オブジェクトを `