Skip to content

Instantly share code, notes, and snippets.

@jmccartie
Created August 12, 2013 23:08
Show Gist options
  • Save jmccartie/6216210 to your computer and use it in GitHub Desktop.
Save jmccartie/6216210 to your computer and use it in GitHub Desktop.
A refactoring of an Anagram finder (tests here: https://github.com/kytrinyx/exercism.io/blob/master/assignments/ruby/anagram/anagram_test.rb) V1 passed, but the `match` method is pretty hard to read. Really what I wanted that method to do was to "select all the words that are anagrams and aren't duplicates." Using Enumerable's `select` method an…
class Anagram
attr_reader :original_word
def initialize(word)
@original_word = word
end
def match(word_list)
matched_words = []
word_list.each do |word|
next if word.downcase == original_word.downcase
matched_words << word if sorted_letters(word) == sorted_letters(original_word)
end
matched_words
end
private
def sorted_letters(word)
word.each_char.map(&:downcase).sort
end
end
class Anagram
attr_reader :original_word
def initialize(word)
@original_word = word
end
def match(word_list)
word_list.select { |word| anagram?(word) && !duplicate?(word) }
end
private
def anagram?(word)
sorted_letters(word) == sorted_letters(original_word)
end
def duplicate?(word)
word.downcase == original_word.downcase
end
def sorted_letters(word)
word.downcase.chars.sort
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment