[英]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/ . 因此,我正在尝试从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)
Use Hash#select : 使用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
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.