bolonomicz
bolonomicz

Reputation: 61

How do I get the keys of a hash whose values equal to given arguments in ruby?

So I am trying to solve this problem from rubeque http://www.rubeque.com/problems/related-keys-of-hash/. Basicaly I just have to get keys of a hash whose values equal to given arguments.I was wondering if you guys can give me some hints? to solving this problem, thank you very much

this is what I have so far

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)

Upvotes: 1

Views: 2135

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118299

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]

Upvotes: 0

falsetru
falsetru

Reputation: 369444

Use 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

Upvotes: 6

Related Questions