-1

我有三个散列,并想输出它们共有的键:

hash1 = {a: "3", b: "2" c: "1"}
hash2 = {b: "2" c: "1"}
hash3 = {b: "2" c: "1", d: "4"}

对于上面的示例,公共键是band c

我需要将其扩展到许多哈希值。最有效和可扩展的方法是什么?

4

2 回答 2

3

是的,你需要类似的东西Hash#intersect。幸运的是,实现起来很简单。

class Hash
  def & another
    result = {}
    self.each do |k, v|
      result[k] = v if another[k] == v
    end
    result
  end
end

hash1 = {a: "3", b: "2", c: "1"}
hash2 = {b: "2", c: "1"}
hash3 = {b: "2", c: "1", d: "4"}

hashes = [hash1, hash2, hash3]


hashes.reduce(:&) # => {:b=>"2", :c=>"1"}

注意:此代码假定键及其对应的值必须匹配才能通过过滤器。如果您只对键本身感兴趣,那么很容易修改代码来做到这一点。我会把它留给你。

于 2013-02-13T12:20:02.313 回答
3
> hashes = [{a: 3, b: 4}, {a: 5, c: 6}, {a: 6, d: 2}]
=> [{:a=>3, :b=>4}, {:a=>5, :c=>6}, {:a=>6, :d=>2}]
> hashes.map(&:keys).inject { |shared, keys| shared & keys }
=> [:a]
于 2013-02-13T12:17:21.583 回答