我如何获得一个哈希值,其值等于ruby中给定的参数? [英] How do I get the keys of a hash whose values equal to given arguments in ruby?

查看:133
本文介绍了我如何获得一个哈希值,其值等于ruby中给定的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从rubeque http:// www .rubeque.com /问题/相关的密钥-的散列/ 。基本上,我只需要得到一个哈希值,其值等于给定的参数。我想知道你们是否可以给我一些提示?为了解决这个问题,非常感谢你



这是我到目前为止

  class Hash 
def keys_of(* args)
key = Array.new
args.each {| x |键<< 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 |值== 1} 
#=> {:a => 1,:d => 1}
{a:1,b:2,c:3,d:1} .select {| key,value |值== 1} .keys
#=> [:a,:d]

{a:1,b:2,c:3,d:1} .select {| key,value | [1,2] .INCLUDE?值} .keys
#=> [:a,:b,:d]






  class Hash 
def keys_of(* args)
选择{| key,value | args.include? value} .keys
end
end


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)

解决方案

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

这篇关于我如何获得一个哈希值,其值等于ruby中给定的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆