Ruby Hash Key with Multiple Values:及时返回最小值

Ruby Hash Key with Multiple Values: returning the minimum value in a timely manner

更新: 我最初是覆盖哈希键,但后来解决了这个问题。感谢大家到目前为止的投入。

现在的问题是迭代需要多长时间才能生成数据:

客户 csv 有 22,000 行。

fiber csv 有 170,000 行。

fiber = CSV.read("fiber.csv", {headers: true})
customers = CSV.read("customers.csv", {headers: true})

hh = Hash.new { |hsh,key| hsh[key] = [] }

#for each customer, loop through all the fiber coords
customers.each do |c|
  fiber.each do |f|
    hh[customer["cid"]].push Haversine.distance(c["lat"], c["lng"], f["lat"], f["lng"])
  end
end

vals = hh.map { |k, v| v.min } #returns the minimum value per row (which I want)

因为我想在 program/command 行之外使用这些值,所以我认为写入 CSV 是一种不错的方法(欢迎提出其他建议)。

但是,由于上面的嵌套循环需要数小时才能完成运行,所以这不是一个理想的方法。

CSV.open("hash_output.csv", "wb") {|csv| vals.each {|elem| csv << [elem]} }

关于如何加快此过程的任何想法?

我认为问题在于您在每个循环中都覆盖了您的名字 space。我会做这样的事情:

hh = Hash.new { |hsh,key| hsh[key] = [] }
#for each customer, loop through all the fiber coords
customers.each do |c|      
  fiber.each do |f|
    hh[c["last Name"]].push Haversine.distance(c["lat"], c["lng"], f["lat"], f["lng"])
  end
end

这样键将是客户的姓氏,值将是距离数组。 所以生成的数据结构将如下所示:

{ 
   "DOE" => [922224.16, 920129.46, 919214.42],
   ...
}