如何在两个哈希/词典之间找到映射

时间:2014-09-02 13:24:07

标签: ruby dictionary hashmap

我有两个哈希/词典。

第一个哈希代表价格桶,看起来像:

hash = {"499 & Under" => "0 TO 499", "500 - 999" => "500 TO 999", "1000 - 1499" => "1000 TO 1499", 
"1500 - 2499" => "1500 TO 2499", "2500 & Above" => "2500 TO *"}

第二个哈希值对应于给定存储桶中的项目数,但它只有桶的下限作为键。它看起来像:

{0=>3605, 500=>3078, 1000=>1656, 1500=>743, 2000=>333}

第二个散列的桶大小为500.另外,我有第二个散列的任何桶中不适合的项目数的信息(在这种情况下大于2500)。

我想在这两个哈希之间创建一个映射。

到目前为止我做了什么:

buckets = {"499 & Under" => "0 TO 499", "500 - 999" => "500 TO 999", "1000 - 1499" => "1000 TO 1499", "1500 - 2499" => "1500 TO 2499", "2500 & Above" => "2500 TO *"}
counts = {0=>3605, 500=>3078, 1000=>1656, 1500=>743, 2000=>333}
gap = 500      ##bucket size of counts hash
after = 681    ##num of items not in any bucket

x = counts
counts = Hash[x.map{|k,v| ["#{k.to_s} TO #{k+gap-1}",v]}]
##{"0 TO 499"=>3605, "500 TO 999"=>3078, "1000 TO 1499"=>1656, "1500 TO 1999"=>743, "2000 TO 2499"=>333}
counts["#{x.keys.max+gap} TO *"] = after
##{"0 TO 499"=>3605, "500 TO 999"=>3078, "1000 TO 1499"=>1656, "1500 TO 1999"=>743, "2000 TO 2499"=>333, "2500 TO *"=>681}

如何合并计数哈希中的两个元素:

"1500 TO 1999"=>743, "2000 TO 2499"=>333

获取计数:

"1500 - 2499" => "1500 TO 2499"

价格桶?

1 个答案:

答案 0 :(得分:0)

也许不是最优雅的方式,但这会奏效:

 hash = {"499 & Under" => "0 TO 499", "500 - 999" => "500 TO 999", "1000 - 1499" => "1000 TO 1499","1500 - 2499" => "1500 TO 2499", "2500 & Above" => "2500 TO *"}
 counts = {0=>3605, 500=>3078, 1000=>1656, 1500=>743, 2000=>333, 2500 => 4}
 value_ranges = value_ranges = Hash[hash.values.map do |v|
                  starting,stopping = v.split("TO").map(&:to_i)
                  [v,(starting..stopping)]
                end]
 #=> {"0 TO 499"=>0..499, "500 TO 999"=>500..999, "1000 TO 1499"=>1000..1499, "1500 TO 2499"=>1500..2499, "2500 TO *"=>2500..0}
 result_hash = Hash[counts.map do |k,v|
                   [value_ranges.collect{|words,range| words if range.include?(k)}.compact.pop || "2500 TO *",v]
               end]
 #=> {"0 TO 499"=>3605, "500 TO 999"=>3078, "1000 TO 1499"=>1656, "1500 TO 2499"=>333, "2500 TO *"=>4}

就像我说它缺乏优雅和可读性,但它产生了结果。不知道这些数据来自何处,但在此结构中构建原始Hash似乎可能比之后合并2更容易。