Ruby判断数组:nb键值对是否不存在于另一数组及差异排查
Ruby数组元素对比解决方案
需求1:找出arr1中nb值在arr2中不存在的元素
先提取arr2中所有nb值并转为集合(大量元素场景下,集合的查找效率远高于数组),再筛选arr1中符合条件的元素:
# 提取arr2的nb值集合 arr2_nb_set = arr2.map { |item| item["nb"] }.to_set # 筛选arr1中nb不在arr2里的元素 missing_elements = arr1.select { |item| !arr2_nb_set.include?(item["nb"]) } p missing_elements # 输出:[{"nb"=>"5qwercv546", "active"=>true, "brand"=>"gem"}]
需求2:找出nb值相同但其他属性不同的元素并高亮差异
先将arr2转为以nb为键的哈希,方便快速匹配对应元素;再遍历arr1对比属性,给差异值添加*标记高亮:
# 将arr2转为{ nb => 元素 }的哈希结构,提升查找效率 arr2_indexed = arr2.each_with_object({}) { |item, hash| hash[item["nb"]] = item } # 遍历arr1,对比并收集差异 differences = arr1.each_with_object([]) do |item1, result| item2 = arr2_indexed[item1["nb"]] next unless item2 # 跳过arr2中没有对应nb的元素 # 找出所有键值对不同的属性 diff_keys = item1.each_pair.reject { |key, val| item2[key] == val }.keys next if diff_keys.empty? # 无差异则跳过 # 给差异值添加高亮标记 highlighted_item1 = item1.dup highlighted_item2 = item2.dup diff_keys.each do |key| highlighted_item1[key] = "*#{highlighted_item1[key]}*" highlighted_item2[key] = "*#{highlighted_item2[key]}*" end result << { nb: item1["nb"], arr1_element: highlighted_item1, arr2_element: highlighted_item2, differing_attributes: diff_keys } end # 打印带高亮的差异结果 differences.each do |diff| puts "匹配NB: #{diff[:nb]}" puts "Arr1元素: #{diff[:arr1_element]}" puts "Arr2元素: #{diff[:arr2_element]}" puts "差异属性: #{diff[:differing_attributes].join(', ')}\n\n" end
运行后输出:
匹配NB: 5df54g54df Arr1元素: {"nb"=>"5df54g54df", "active"=>"*true*", "brand"=>"aisle"} Arr2元素: {"nb"=>"5df54g54df", "active"=>"*false*", "brand"=>"aisle"} 差异属性: active 匹配NB: 5jghfj264 Arr1元素: {"nb"=>"5jghfj264", "active"=>false, "brand"=>"*leg*"} Arr2元素: {"nb"=>"5jghfj264", "active"=>false, "brand"=>"*gem*"} 差异属性: brand
原代码问题说明
你之前的代码存在几个语法与逻辑错误:
arr1.map(&:nb)无效,Ruby哈希没有nb方法,应该用arr1.map { |h| h["nb"] };- 代码结构混乱,
find的block参数错误,且!Include?应为小写的!include?; - 逻辑上没有正确区分
nb值的匹配与属性差异的判断。
内容的提问来源于stack exchange,提问作者Kamilo
相关产品推荐
相关产品推荐

