【问题标题】:compare 2 hashes in ruby [duplicate]比较红宝石中的2个哈希[重复]
【发布时间】:2011-05-30 10:47:27
【问题描述】:

可能重复:
Comparing ruby hashes

如何比较两个哈希值并仅在名称匹配正确时才显示。

element1 = {:name => "Original", :description => "The original one!"}
element2 = {:name => "Original", :description => ""}

【问题讨论】:

  • 您能否添加一个输出示例,您应该得到这两个哈希值?

标签: ruby hash


【解决方案1】:

如果你想要一个反向的差异,那么你可以试试这个。

class Hash
  def in_both(other)
    self.keys.inject({}) do |memo, key|
      memo[key] = self[key] if self[key] == other[key]
      memo
    end
  end
end

> element1.in_both(element2)
=> {:name=>"Original"}

或者更短的

element1.select{|k,v| element2[k]==v}

【讨论】:

    【解决方案2】:

    我不知道这是不是你要找的东西

    element1[:name] == element2[:name]
    

    或者更具体一些,请。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-18
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2012-10-17
      • 1970-01-01
      • 2011-09-23
      相关资源
      最近更新 更多