Skip to content

Instantly share code, notes, and snippets.

@shepmaster
Forked from alekst/anagram
Last active December 22, 2015 06:18
Show Gist options
  • Save shepmaster/6429895 to your computer and use it in GitHub Desktop.
Save shepmaster/6429895 to your computer and use it in GitHub Desktop.
class AnagramTest < MiniTest::Unit::TestCase
class Anagram
def initialize(word)
@word = word
# If you create the array here, then the results will be
# collected over multiple calls to `match`. Not sure if that is
# intended or not, so I'll assume it's ok to change.
end
def match(candidates)
# This never changes during the loop, so I'd extract it. Could
# maybe even be in the constructor.
matching_letters = letters(@word)
# Almost any time you have the pattern `create collection;
# manipulate collection; return collection`, there's a
# functional replacement.
anagrams = candidates.select do |candidate|
# The inside of blocks is usually indented
letters(candidate) == matching_letters
# I prefer to do exactly one thing when processing arrays, I
# find it's easier to follow in the future.
end
# I like using the array / set operators. Here I just want to
# make sure the results never have the original word. This also
# removes a conditional.
anagrams - [@word]
end
# Extract a little helper, just to make sure we are always doing
# the same to both sides.
def letters(word)
# Not sure that we need the join here.
word.to_s.downcase.chars.sort
# The to_s is a good call! That way you are sure you have a string.
end
private :letters
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment