ruby学習メモ
クロージャブロック
class TestClass def name @name end def initialize(label, &action) @name = label @action = action end def call_action puts "start call_action" @action.call(self) end end
テスト1
test1 = TestClass.new("test") { name } test1.name test1.call_action irb(main):429:0* test1 = TestClass.new("test") { name } => #<TestClass:0x325c198 @name="test", @action=#<Proc:0x0325c1e8@(irb):429>> irb(main):430:0> test1.name => "test" irb(main):431:0> test1.call_action start call_action => nil
TestClass のメンバ name 参照は nil
テスト2
anyValue = "123" test2 = TestClass.new("test") { anyValue } test2.call_action irb(main):432:0> anyValue = "123" => "123" irb(main):433:0> test2 = TestClass.new("test") { anyValue } => #<TestClass:0x324feac @name="test", @action=#<Proc:0x0324ff10@(irb):433>> irb(main):434:0> test2.call_action start call_action => "123"
ローカル変数 anyValue の参照は正常出力
プログラミング Ruby第2版 より
ブロックには(したがってProcオブジェクトには)、そのブロックが「定義された」全てのコンテキスト──self の値・メソッド・変数・スコープ内定数──が関連付けられます。
def n_times(thing) return lambda {|n| thing * n} end p1 = n_times(23) p1.call(3) => 69 p1.call(4) => 92 n_times("Hello ") p2.call(3) => "Hello Hello Hello "