I recently had to write an anagram solver for a job interview. Here is my code.
class Anagram
def self.resolves?(first_word, second_word)
@letter_counts = {}
# Assuming that anagrams aren't case sensitive.
first_word.downcase!
second_word.downcase!
count_letters(first_word, 1)
count_letters(second_word, -1)
(sum_of_counts == 0)
end
private
def self.sum_of_counts
@letter_counts.inject(0){|sum, n| sum + n[1]}
end
def self.count_letters(aword, incrementer)
aword.each_byte {|c| @letter_counts[c].nil? ? @letter_counts[c] = 1 : @letter_counts[c]+=incrementer }
end
end
puts Anagram.resolves?('dog','cat')
puts Anagram.resolves?('dog','god')
puts Anagram.resolves?('Jim','Jones')
puts Anagram.resolves?('Hello','olleH')
I particularly don't like the count_letters method and the checking of the existence of the hash value. Where can I improve this code so that's it's more idiomatic Ruby?
Thanks in advance.