2016-08-03 58 views
1

我在舊版應用程序中使用yield的方式讓我不明白。我可以用一些幫助來解釋。我已閱讀了大部分關於Ruby yield的SO結果,但在此情況下無法理解。謝謝。在這個Ruby方法中yield有什麼作用?

def find_all_from_source(source_id) 
    joins, conditions = invoke_records_from_source(source_id) 
    find(:all, :select => 「#{self.table_name}」, :joins => joins, :conditions => conditions).each do |record| 
    yield record 
    end 
end 

result = {} 
model.find_all_from_source(source_id) do |r| 
    result[r.id] = {'attribute' => r.attribute } 
end 
+0

因此,我增加相關的註釋一些代碼,@sergio做錯過塊。 – jmscholen

回答

2

find_all_from_source顯然是爲了與處理由find以某種方式返回的記錄塊被調用。 yield調用每個記錄上的塊。

這種方法也可以寫成這樣unidiomatic方式,以避免Ruby的難以遵循隱性塊語法:

def find_all_from_source(source_id, some_more_arguments, &block) 
    joins, conditions = invoke_records_from_source(source_id, some_more_arguments) 
    find(:all, :select => 「#{self.table_name}」, :joins => joins, :conditions => conditions).each do |record| 
    block.call record 
    end 
end 
+1

「我希望它失敗」 - 除非'find'返回任何內容,這就隱藏了錯誤。或者也許他認爲這個塊是一個微不足道的細節,並將它隱藏在'some_more_arguments'之後。 –

+0

因此,在添加的代碼塊中,'yield record'被替換爲'do | r | result [r.id] = {'attribute'=> r.attribute} end'代碼塊? @SergioTulentsev @DaveSchweisguth – jmscholen

+0

完全不是「替換」的,但是,塊的運行在塊參數「r」設置爲yield的參數「record」。 –

相關問題