Skip to content

Instantly share code, notes, and snippets.

@damonmcminn
Created February 25, 2017 13:34
Show Gist options
  • Select an option

  • Save damonmcminn/9c5ac0798c3a4077024855cce5d137f6 to your computer and use it in GitHub Desktop.

Select an option

Save damonmcminn/9c5ac0798c3a4077024855cce5d137f6 to your computer and use it in GitHub Desktop.
Anagram Detector
class Anagram
def initialize(str)
@str = str
end
def normalized
@str.split('?').map do |word|
# replace all non-alphabet characters with nothing
word.downcase.gsub(/[^[:alpha:]]/, '')
end
end
def counts
normalized.map do |word|
char_counts = {}
word.chars.each do |char|
if char_counts[char].nil?
char_counts[char] = 1
else
char_counts[char] += 1
end
end
char_counts
end
end
def is_anagram?
result =
if counts.first == counts.last
'is an anagram of'
else
'is NOT an anagram of'
end
@str.gsub('?', result)
end
end
STDIN.readlines.each do |input|
puts Anagram.new(input).is_anagram?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment