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

时间:2013-08-21 13:57:37

标签: ruby-on-rails ruby class loops hash

所以我试图从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)

2 个答案:

答案 0 :(得分:5)

使用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

答案 1 :(得分: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]