2011-11-20 74 views

回答

9

閉包可以修改對象的範圍,就像這樣:

require 'benchmark' 

a = nil 
puts Benchmark.measure { a = "a" * 1_000_000 } 
puts a.size 

# => 0.000000 0.000000 0.000000 ( 0.004865) 
# => 1000000 
+0

因此,關閉有一個可寫的指針,指向傳遞給它們的內容?並且可以關閉修改@a和@@ a,假設它們是在關閉之外定義的。 – justingordon

+0

@justingordon:是的,他們可以。 – Miikka

+3

Yuck。我真的希望Benchmark會返回類似於''[time,result]''。然後你可以:'時間,a = Benchmark.measure {...}' – devth

0

隨着https://github.com/igorkasyanchuk/benchmark_methods

沒有更多這樣的代碼:

t = Time.now 
user.calculate_report 
puts Time.now - t 

現在你可以這樣做:

benchmark :calculate_report # in class 

只需調用你的方法

user.calculate_report