开发者

compare 2 hashes in ruby [duplicate]

开发者 https://www.devze.com 2023-03-09 00:35 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Comparing ruby hashes How can I compare two hashes and show only if name was matching correctly.
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Comparing ruby hashes

How can I compare two hashes and show only if name was matching correctly.

element1 = {:name => "Original", :description => "The original one!"}
element2 = {:name => "Original", :description =>开发者_如何学运维 ""}


If a reverse of a diff is what you want then you could try this.

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"}

or the much shorter

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


I don't know if this is what you're looking for

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

Or be more specific, please.

0

精彩评论

暂无评论...
验证码 换一张
取 消