简体   繁体   English

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

[英]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.

相关问题 从值是ruby中的数组的哈希访问键 - Accessing keys from an hash whose values are arrays in ruby Ruby / Rails:如何将键值字符串(包括数组值)转换为有效哈希 - Ruby/Rails: How do I convert a keys-values string(with array value included) to valid hash 如何查找 Ruby hash 的“零”值并将其替换为“无”或 0? - How do I find and replace 'nil' values of Ruby hash with “None” or 0? 如何在给定嵌套键的 Ruby 哈希中获取和设置值? - How to do get and set values in Ruby Hashes of a given nested key? 在 hash 中使用单个 integer 进行搜索,其键是 Ruby 中的范围 - Searching using a single integer in a hash whose keys are ranges in Ruby 如何从值数组中搜索Ruby哈希,然后根据发现结果返回哈希? - How do I search a Ruby hash from an array of values, and then return a hash based on the findings? 如何在Ruby中建立目录名称(作为键)和文件名称(作为值)的哈希? - How to build a hash of directory names as keys and file names as values in Ruby? 如何在ruby中按位置获取哈希值? - how to get hash values by position in ruby? Ruby-如何根据给定日期(=键)对哈希值求和? - Ruby - How to sum values of a hash based on a given date (=key)? 如何将Ruby哈希输出为Javascript? - How do I output a Ruby hash as Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM