gpt4 book ai didi

Ruby 数组注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:07 26 4
gpt4 key购买 nike

我正在尝试使用注入(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

最佳答案

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

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

关于Ruby 数组注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8829539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com