繁体   English   中英

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

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

因此,我正在尝试从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)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM