【问题标题】:How do I get the keys of a hash whose values equal to given arguments in ruby?如何获取值等于 ruby​​ 中给定参数的哈希键?
【发布时间】:2013-08-23 22:38:46
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 不错(y),我喜欢这个
    • 使用args.include?(value) 使最后一次测试通过
    • @Satya,谢谢,我错过了。
    【解决方案2】:
    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多