【问题标题】:Compare two complex hashes in ruby比较 ruby​​ 中的两个复杂哈希
【发布时间】:2014-07-20 16:20:14
【问题描述】:

我正在尝试在 ruby​​ 中递归地比较两个哈希值,但有一些警告。我不能简单地比较字符串,因为一个哈希使用 nil,一个使用 0 等等

这是我的功能:

    def compare_yaml(yaml1,yaml2)
    f = ["f", "false", false]
    t = ["t", "true", true]
    nil_equivalents = [0, "", [], {}, nil, " "]
    return true if yaml1 == yaml2

    if (f.include?(yaml1) and f.include?(yaml2)) or (t.include?(yaml1) and t.include?(yaml2))
      return true
    end
    if (nil_equivalents.include?(yaml1) && nil_equivalents.include?(yaml2)) then
        # puts "we found a nil"
    return true
    end
    if (yaml1.class == yaml2.class)
        if yaml1.class.to_s == "Hash"
            puts "gotta hash" + yaml1.to_s
            # a = yaml1.inspect
            # b = yaml2.inspect
            yaml1.keys.map{|k| (yaml2.keys.include? k)? compare_yaml(yaml1[k], yaml2[k]) : false}.reduce{|n,m| n&&m}
        end
        if yaml1.class.to_s == "Array"
            return false unless yaml1.length == yaml2.length
            # yaml1.sort!
            # yaml2.sort!
            return yaml1.zip(yaml2).map { |e| compare_yaml(e[0],e[1])}.reduce{|n,m| n&&m}

        end

    end

return false
end

我尝试使用以下行来测试:

compare_yaml({"Computer"=>{"Axiom Tech Co"=>{"Windows 2003"=>[["x86 Family 6 Model 14 Stepping 8 ", nil, 1]]}, "Dell"=>{"Windows 2003"=>[["x86 Family 15 Model 4 Stepping 1 ", nil, 1]]}}, "Desktop"=>{"Hewlett-Packard"=>{"Windows 7 Pro"=>[["Intel Core i7 870 2.93GHz", 1, 1]], "Windows XP Pro"=>[["AMD Athlon Dual Core 4450B", 1, 1]]}}, "Laptop"=>{"Hewlett-Packard"=>{"Windows 7 Pro"=>[["Intel Core i5 M 460 2.53GHz", 1, 1]]}}},{"Computer"=>{"Axiom Tech Co"=>{"Windows 2003"=>[["x86 Family 6 Model 14 Stepping 8", 0, 1]]}, "Dell"=>{"Windows 2003"=>[["x86 Family 15 Model 4 Stepping 1", 0, 1]]}}, "Desktop"=>{"Hewlett Packard"=>{"Windows 7 Pro"=>[["Intel Core i7 870 2.93GHz", 1, 1]], "Windows XP Pro"=>[["AMD Athlon Dual Core 4450B", 1, 1]]}}, "Laptop"=>{"Hewlett Packard"=>{"Windows 7 Pro"=>[["Intel Core i5 M 460 2.53GHz", 1, 1]]}}})

应该返回true,但它没有

有人可以帮忙吗?

【问题讨论】:

  • 如何得出哈希相等的结论?

标签: ruby hash yaml


【解决方案1】:

您的样本应该返回 false,因为:

  1. "x86 Family 6 Model 14 Stepping 8 " != "x86 Family 6 Model 14 Stepping 8"(第一个末尾有空格)
  2. "x86 Family 15 Model 4 Stepping 1 " != "x86 Family 15 Model 4 Stepping 1"(同样的事情)
  3. {"Hewlett-Packard"=>{"Windows 7 Pro"=>[["Intel Core i5 M 460 2.53GHz", 1, 1]]}}} != {"Hewlett Packard"=>{"Windows 7 Pro"=>[["Intel Core i7 870 2.93GHz", 1, 1]], "Windows XP Pro"=>[["AMD Athlon Dual Core 4450B", 1, 1]]}}(第一个缺少“Windows XP Pro”)
  4. "Hewlett Packard" != "Hewlett-Packard"

不断……

底线 - 您的示例应该返回 true...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多