将缺少的哈希值从一个数组添加到另一个数组

时间:2016-09-22 18:18:21

标签: ruby

我有两个红宝石阵列。 source_array以哈希的形式包含我的所有源数据。我有一个user_array,其中包含用户选择的数据子集。我需要合并/组合两个数组以形成一个新的result_array,保留user_array中的所有哈希值,并从source_array中添加那些在user_array中不存在的哈希值。

源数组:

   source_array = [ 
      {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>""}, 
      {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
      {:category=>"truck", :make=>"ford", :model=>"F350", :notes=>""},
      {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", :notes=>""}
    ]

目标阵列:

target_array = [ 
  {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."}
]

结果数组:

result_array = [ 
      {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>""}, 
      {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
      {:category=>"truck", :make=>"ford", :model=>"F350", :notes=>""},
      {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."}
    ]

感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

我们得到了

source_arr =
[ 
  {:category=>"truck", :make=>"ford",  :model=>"F150", :notes=>""}, 
  {:category=>"truck", :make=>"ford",  :model=>"F250", :notes=>""}, 
  {:category=>"truck", :make=>"ford",  :model=>"F350", :notes=>""},
  {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", :notes=>""}
]

target_arr =
[ 
  {:category=>"truck", :make=>"ford", :model=>"F150",
   :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."},
  {:category=>"truck", :make=>"ford",  :model=>"F350", :notes=>"what a beast!"}
]

首先使用要匹配的键构造一个哈希值。

target_hashes = target_arr.map { |h| h.reject { |k,_| k == :notes } }
  #=> [{:category=>"truck", :make=>"ford", :model=>"F150"},
  #    {:category=>"truck", :make=>"ford", :model=>"F350"}]

接下来构造一个数组,其中包含source_arr中与target_hashes中所有哈希键不匹配的所有哈希值。

sources_to_add = source_arr.reject { |h|
  target_hashes.include?(h.reject {|k,_| k == :notes }) }
  #=> [{:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""},
  #    {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", :notes=>""}]

现在构建所需的数组。

target_arr + sources_to_add
  #=> [{:category=>"truck", :make=>"ford", :model=>"F150",
  #     :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."},
  #    {:category=>"truck", :make=>"ford", :model=>"F350",
  #     :notes=>"what a beast!"},
  #    {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""},
  #    {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500",
  #     :notes=>""}]

如果您不想修改target_arr

target_arr += sources_to_add

如果你这样做。