2012-07-11 66 views
2

我有一段代碼,如果需要,應在運行時再次對其進行評估。如何將proc存儲到變量中(稍後調用它)

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對象會很高興地檢查一堆事情,讓它們決定用什麼來更新它們的值。當然,該塊是我寫的東西(我認爲)他們不應該能夠做我沒有計劃的東西...

這個例子有點奇怪。基本上可以存儲一段代碼(這只是我相信的一個Proc),然後再重新評估它。

回答

4

你什麼請求正是塊的用途。您只需使用「調用」存儲的塊。下面是一個例子:

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 
2

也許我失去了一些東西,但爲什麼不只是存儲block在您的實例變量:

def make_initial_attributes(&block) 
    @some_block = block 
end 

,然後,因爲blockProc,只是call它:

def rebuild_attributes 
    @some_block.call 
end 
+0

呵呵,沒想到是那麼簡單! – MxyL 2012-07-11 06:17:47

相關問題