Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在散列中查找重复的键?_Ruby_Hash_Unique - Fatal编程技术网

Ruby 在散列中查找重复的键?

Ruby 在散列中查找重复的键?,ruby,hash,unique,Ruby,Hash,Unique,为了简化事情,假设我有下面的散列 我想找到多个散列中的键以及散列的名称。因此,理想情况下,我希望以 A is also in a A is also in b B is also in a B is also in b D is also in b D is also in c E is also in b E is also in c 我能想到的唯一方法是:将所有键放在一个数组中,排序,删除唯一的元素,搜索包含剩余数组元素的每个哈希 我想这有点复杂和粗糙 问题 有没有更简单的

为了简化事情,假设我有下面的散列

我想找到多个散列中的键以及散列的名称。因此,理想情况下,我希望以

A is also in  a
A is also in  b
B is also in  a
B is also in  b
D is also in  b
D is also in  c
E is also in  b
E is also in  c
我能想到的唯一方法是:将所有键放在一个数组中,排序,删除唯一的元素,搜索包含剩余数组元素的每个哈希

我想这有点复杂和粗糙

问题

有没有更简单的方法跨哈希查找重复键

!/usr/bin/ruby                                                                                          

require 'ap'

a = {}
b = {}
c = {}

a["A"] = 1
a["B"] = 1
a["C"] = 1

b["A"] = 1
b["B"] = 1
b["D"] = 1
b["E"] = 1

c["D"] = 1
c["E"] = 1
c["F"] = 1

要查找具有特定键的哈希,可以执行以下操作

def find_key_in list_of_hashes, key
  list_of_hashes.select { |one_hash| one_hash.detect { |k,v| k == key }}
end
可以这样称呼:

irb(main):016:0> find_key_in [{a: 3, b: 2}, {b: 3, x: 4} ], :x
=> [{:b=>3, :x=>4}]
打印哈希值的名称是一个难题

像这样的

arr = { 'a' => a, 'b' => b, 'c' =>c}
#=> {"a"=>{"A"=>1, "B"=>1, "C"=>1}, "b"=>{"A"=>1, "B"=>1, "D"=>1, "E"=>1}, "c"=>{"D"=>1, "E"=>1, "F"=>1}}

def my_method(letter, arr)
 arr.map { |el|  "#{letter} is in #{el[0]}" if !el[1]["#{letter}"].nil? }.compact
end
例如:

my_method("A", arr)
#=> ["A is in a", "A is in b"]

您可以构建另一个散列来存储每个键及其散列:

keys = Hash.new { |hash, key| hash[key] = [] }
a.each_key { |k| keys[k] << :a }
b.each_key { |k| keys[k] << :b }
c.each_key { |k| keys[k] << :c }
要获得预期输出,请执行以下操作:

keys.each do |key, hashes|
  next if hashes.size < 2
  hashes.each { |hash| puts "#{key} is also in #{hash}" }
end

你试过什么吗?你能分享一下你的努力吗?哈希的名字是什么?哈希在Ruby中没有名称。
keys.each do |key, hashes|
  next if hashes.size < 2
  hashes.each { |hash| puts "#{key} is also in #{hash}" }
end
A is also in a
A is also in b
B is also in a
B is also in b
D is also in b
D is also in c
E is also in b
E is also in c