1

I am trying to log the average running time of 10 threads by using the inject method but it's giving me this error:

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

Here's the code:

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
0

2 Answers 2

3

You need to provide an initial value for inject in this case, since if you don't, the initial value is simply the first element in the array:

puts threads.inject(0) { |sum, e| sum + e.value}.to_f / threads.size
Sign up to request clarification or add additional context in comments.

Comments

2

You didn't provide an initial value for sum in

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

Fix it with

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.