我正在閱讀Eloquent Ruby書(迄今爲止令人敬畏的書),並且不理解關於集合,參數和範圍的一節。下面的代碼...具有參數的Ruby塊
class SomeApplication
# Rest of the class omitted...
def do_something
with_logging('load', nil) { @doc = Document.load('book') }
# Do something with the document...
with_logging('save', @doc) { |the_object| the_object.save }
end
def with_logging(description, the_object)
begin
@logger.debug("Starting #{description}")
yield(the_object)
@logger.debug("Completed #{description}")
rescue
@logger.error("#{description} failed!!")
raise
end
end
end
書上說的代碼是比它需要的是因爲@doc是代碼塊中自動顯示更加複雜。所以沒有必要把它作爲一個論點來傳遞。
我不明白他在說什麼,該@doc或|the_object|
這PARAM。在改變它以消除不必要的複雜性後,這段代碼會是什麼樣子?
還是意味着在於用with_logging('load', nil)
創建@doc是什麼仍是可見的?即使是這種情況,我也不確定底部的with_logging
方法如何訪問它。