Ruby数组注入

时间:2012-01-12 02:55:46

标签: ruby

我试图通过使用inject方法记录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

2 个答案:

答案 0 :(得分:3)

在这种情况下,您需要为inject提供初始值,因为如果不这样做,初始值只是数组中的第一个元素:

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

答案 1 :(得分:2)

您没有在

中提供sum的初始值
threads.inject() { |sum, e| sum + e.value}.to_f / threads.size

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