Reputation: 61
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
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
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