如何获取其值等于ruby中给定参数的哈希的键?

所以我试图从rubeque http://www.rubeque.com/problems/related-keys-of-hash/解决这个问题。 Basicaly我只需要得到哈希的键,其值等于给定的参数。我想知道你们是否可以给我一些提示? 解决这个问题,非常感谢你

这就是我到目前为止所拥有的

class Hash def keys_of(*args) key = Array.new args.each { |x| key << x} key.each { |x,y| x if y == key} end end assert_equal [:a], {a: 1, b: 2, c: 3}.keys_of(1) assert_equal [:a, :d], {a: 1, b: 2, c: 3, d: 1}.keys_of(1) assert_equal [:a, :b, :d], {a: 1, b: 2, c: 3, d: 1}.keys_of(1, 2) 

使用哈希#select :

 {a: 1, b: 2, c: 3, d: 1}.select { |key, value| value == 1 } # => {:a=>1, :d=>1} {a: 1, b: 2, c: 3, d: 1}.select { |key, value| value == 1 }.keys # => [:a, :d] {a: 1, b: 2, c: 3, d: 1}.select { |key, value| [1,2].include? value }.keys #=> [:a, :b, :d] 

 class Hash def keys_of(*args) select { |key, value| args.include? value }.keys end end 
 h = {a: 1, b: 2, c: 3, d: 1} p h.each_with_object([]){|(k,v),ar| ar<> [:a, :b, :d]