Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save philsof/b04fd16e8b6b9013c435 to your computer and use it in GitHub Desktop.
Save philsof/b04fd16e8b6b9013c435 to your computer and use it in GitHub Desktop.

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 of map. Why? Because map 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 your find_anagrams method, map is not a good choice.

  • BUT, your logic is sound. You are iterating through the list_arr, checking each object with your anagrams? 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 your find_anagrams method? You need to iterate through list_arr and return an array that contains all of the words for which anagrams? 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 is select. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment