2

必要に応じて実行時に再度評価する必要があるコード ブロックがあります。

class Test

    def initialize
        @some_block = nil
    end

    def make_initial_attributes(&block)
       # do stuff with the supplied block, and then store the block somewhere
       # for later
    end

    def rebuild_attributes
       # grab that stored block and evaluate it again
    end 
end

起動時に作成される Test オブジェクトがありますが、その後、プログラム全体で、起動時に渡したブロックを実行して、それらを「更新」する必要がある場合があります。

おそらくプログラムの状態が変化したため、これらの Test オブジェクトは喜んで一連のことをチェックし、値を更新する対象を決定できるようにします。もちろん、ブロックは私が書くものなので(私は思う)、私が計画していないことを彼らができるようにするべきではありません...

例は少し奇妙です。基本的に、コードのブロック (これは単なる Proc だと思います) を保存し、後で再評価することは可能ですか。

4

2 に答える 2

4

あなたが要求するのは、まさにブロックの目的です。保存されたブロックに「call」を使用するだけです。次に例を示します。

class Test
    def initialize
        @some_block = nil
    end

    def make_initial_attributes(&block)
      @some_block = block
       # do stuff with the supplied block, and then store the block somewhere
       # for later
    end

    def rebuild_attributes
      @some_block.call(1)
       # grab that stored block and evaluate it again
    end
end

test = Test.new
test.make_initial_attributes do |i|
  puts i
end
test.rebuild_attributes  # 1

test.make_initial_attributes do |i|
  puts i+1
end
test.rebuild_attributes # 2
于 2012-07-11T05:54:37.907 に答える
2

たぶん私は何かが欠けているかもしれませんがblock、インスタンス変数に保存しないのはなぜですか:

def make_initial_attributes(&block)
    @some_block = block
end

そして、blockは aProcであるため、それだけcallです:

def rebuild_attributes
    @some_block.call
end 
于 2012-07-11T05:54:28.123 に答える