2012-01-12 147 views
1

我想通過注射的方法來記錄的10個線程的平均運行時間,但它給我這個錯誤:紅寶石陣列注入

undefined method `+' for #<Thread:0x10b211590 dead> (NoMethodError) 
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:301:in `inject' 
    from client_test.rb:13:in `each' 
    from client_test.rb:13:in `inject' 
    from client_test.rb:13 

下面的代碼:

require 'open-uri' 
program_start_time = Time.now 
threads = 10.times.map do 
    Thread.new do 
    time = Time.now 
    open('http://ca.yahoo.com/?p=us').read.length 
    Time.now-time 
    end 
end 

threads.map &:join 
puts threads.inject() { |sum, e| sum + e.value}.to_f/threads.size 
puts Time.now - program_start_time 

回答

3

您需要在這種情況下爲inject提供初始值,因爲如果不這樣做,初始值就是數組中的第一個元素:

puts threads.inject(0) { |sum, e| sum + e.value}.to_f/threads.size 
2

你沒有在

threads.inject() { |sum, e| sum + e.value}.to_f/threads.size 

修復提供總和的初始值它

threads.inject(0) { |sum, e| sum + e.value}.to_f/threads.size