我想从哈希中获取具有相同值的哈希中的键名

时间:2017-06-08 04:17:51

标签: ruby

{"Amar"=>20,"Benton"=>14,"John"=>32,"Sunny"=>28,"Edward"=>19,"Leon"=>12,"Ram"=>19,"David"=>28}

上面的哈希有名字和年龄,我想得到红宝石中年龄相同的名字

4 个答案:

答案 0 :(得分:2)

试试这个。

hash = {"name1"=>12, "name2"=>13, "name3"=>12}

groups = {}
hash.each do |k, v|
  groups[v] = groups[v] || []
  groups[v].push(k)
end

答案 1 :(得分:2)

一种解决方案是创建一个哈希,其中age为密钥,名称数组为值:

Command Line Tools

请注意,如果您希望获得所有19岁的人,则可以使用names = {"Amar"=>20, "Benton"=>14, "John"=>32, "Sunny"=>28, "Edward"=>19, "Leon"=>12, "Ram"=>19, "David"=>28} ages = {} names.each do |key, value| ages[value] ||= [] ages[value] << key end puts ages #=> {20=>["Amar"], 14=>["Benton"], 32=>["John"], 28=>["Sunny", "David"], 19=>["Edward", "Ram"], 12=>["Leon"]}

答案 2 :(得分:2)

hash = {"Amar"=>20,"Benton"=>14,"John"=>32,"Sunny"=>28,"Edward"=>19,"Leon"=>12,"Ram"=>19,"David"=>28}

hash.keys.group_by { |k| hash[k] }.values.select { |g| g.size > 1 }
# => [["Sunny", "David"], ["Edward", "Ram"]] 

Sunny和大卫的年龄相同,爱德华和拉姆也是如此。

答案 3 :(得分:1)

为你的哈希

 names_hash = {"Amar"=>20,"Benton"=>14,
  "John"=>32,"Sunny"=>28,
  "Edward"=>19,"Leon"=>12,
  "Ram"=>19,"David"=>28}

您始终可以定义一个为年龄

提供所需名称的方法
def names_for_age(age, hash = {})
  hash.inject({}) do |container, (k,v)|
    container[v] ||= []
    container[v] << k
    container
  end[age]
end

所以,现在你可以将名字改为

names_for_age(10, names_hash)