Good stuff. Here are my notes on your code:
-
Your anagrams? method is sweet. You got this one 100%.
-
You chose to use map to iterate through each word in
list_arr
. This works, but it is a misuse ofmap
. Why? Becausemap
has a specific function: to iterate through an existing array, perform the same action on each object in the existing array, and return a new array that contains the resulting objects. Since you do not need to do this in yourfind_anagrams
method,map
is not a good choice. -
BUT, your logic is sound. You are iterating through the
list_arr
, checking each object with youranagrams?
method, which is exactly what you should do. So the good news is: you know how to get this done; your logic and approach are sound, and you know how to utilize a method (anagrams?
) inside another method (find_anagrams
), which shows you understand that each of your methods should have exactly one responsibility. -
So what would be a better choice than
map
in this situation? Ask yourself: what do you need to do in yourfind_anagrams
method? You need to iterate throughlist_arr
and return an array that contains all of the words for whichanagrams?
is true. Is there a built-in array method that would pass each array object to a code block, and return a new array that contains only the objects that meet the conditions in that code block? Yes! It isselect
. Check this out:def find_anagrams(word, list_arr) list_arr.select{|check| anagrams?(word, check)} end
Notice that, since the return value of select
is an array of all the objects for which the code block returns true
, there is now no need for a match_array
variable. That is pretty sweet. Here are the docs on select. Be sure to utilize this powerful method!
Bottom line: You are clearly getting the hang of this. Now you just need to get more specific on which public Ruby method is the best choice in any given situation. Even though map
could often do the job, you should only use map
for what it is made for. I strongly recommend you read through the Ruby Enumerable module docs, so that you are fully aware of all of the public methods available to you. Knowledge is power!
Any questions let me know.
-Phil