Skip to content

Instantly share code, notes, and snippets.

@dustinbrownman
Created August 29, 2013 16:22
Show Gist options
  • Select an option

  • Save dustinbrownman/6380278 to your computer and use it in GitHub Desktop.

Select an option

Save dustinbrownman/6380278 to your computer and use it in GitHub Desktop.
Expects a word and an array of possible anagrams of that word. Returns an array of all true anagrams.
def anagrams(word, possible_anagrams)
unless possible_anagrams.is_a?(Array) || possible_anagrams.all? { |anagram| anagram.is_a?(String) }
raise TypeError.new("The possible anagrams must be an array")
end
possible_anagrams.find_all do |anagram|
word.chars.sort == anagram.chars.sort
end
end
require 'rspec'
require 'anagrams'
describe 'anagrams' do
it 'finds a simple match' do
anagrams("abc", ["cba"]).should eq ["cba"]
end
it 'finds all anagrams of a word from the list' do
anagrams("abc", ["cba", "bca", "abc", "ac", "adc"]).should eq ["cba", "bca", "abc"]
end
it 'raises an exception if it does not get a string' do
expect { anagram(2) }.to raise_exception
end
it 'raises an exception if it does not get an array of strings for the second arguement' do
expect { anagram("abc", [2, 3, 4]) }.to raise_exception
expect { anagram("abc", "abc") }.to raise_exception
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment