1

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

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

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)
4

2 回答 2

6

使用Hash#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
于 2013-08-21T13:59:53.177 回答
0
h = {a: 1, b: 2, c: 3, d: 1}
p h.each_with_object([]){|(k,v),ar| ar<<k if [1,2].member?(v)}
# >> [:a, :b, :d]
于 2013-08-21T14:14:09.947 回答