当值与模式匹配时,从hash返回一个键数组



我正在尝试运行以下散列

my_family_pets_ages = {"Evi" => 6, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0, "Ditto" => 3}

并返回键的数组,该数组的值与指定的年龄整数相匹配。例如,如果我想找到所有3岁的宠物,它会只返回它们的名字。

["Hoobie", "Ditto"]

我有以下方法,但我似乎无法获得只返回密钥数组的方法,但在这样的数组中,我一直只获得密钥=>值:

["Hoobie"=>3, "Ditto"=>3]

这是我到目前为止的方法

def my_hash_finding_method(source, thing_to_find)
  source.select {|name, age| name if age == thing_to_find}
end

有指针吗?我被困在如何只返回密钥

只需使用#select,然后使用#keys即可获得匹配密钥的数组:

def my_hash_finding_method(source, thing_to_find)
  source.select { |name, age| age == thing_to_find }.keys
end

有关详细信息,请参阅哈希#密钥。

最新更新