Dirtsquad
Dirtsquad

Reputation: 11

return an array of keys from hash when values match pattern

I am trying to run through the following hash

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

and return an array of the keys whose values match a specified integer for age. So, for example, if I wanted to find all of the pets that are 3 years old, it would return an array of just their names.

["Hoobie", "Ditto"]

I have the following method, but I can't seem to get the method to return an array of just the keys, but I keep just getting the key => value in an array like this:

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

Here is the method I have so far

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

Any pointers? I'm stuck on how to return only the keys

Upvotes: 0

Views: 3670

Answers (1)

theunraveler
theunraveler

Reputation: 3284

Just use #select, then #keys to get an array of the matching keys:

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

See Hash#keys for more information.

Upvotes: 3

Related Questions