0

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

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Please add an explanation of this . The OP is obviously new to ruby so an explanation will make your answer more useful to them as well as other users with the same question.
thanks so much! I didn't know you could call the keys method on that entire block. very helpful!
The block just returns a Hash, so you can call any Hash instance methods you'd like on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.