Skip to content

Instantly share code, notes, and snippets.

@randito
Created August 23, 2012 16:08
Show Gist options
  • Save randito/3438114 to your computer and use it in GitHub Desktop.
Save randito/3438114 to your computer and use it in GitHub Desktop.
Little anagram checker. Had to find out if this tweet was true: https://twitter.com/crampell/status/238620771398864897
class String
def anagram?(other)
letter_count(self) == letter_count(other) # uses hash equivelence
end
private
# "wwaax" => { "w" => 2, "a" => 2, "x" => 1 }.. all others 0
def letter_count(str)
str.downcase.each_char.inject(Hash.new(0)) { |h, ch| h[ch] += 1; h }
end
end
unless defined?(assert)
def assert(cond, msg="Failed assertion")
raise msg unless cond
end
end
assert "abc".anagram?("cba")
assert "Abc".anagram?("Cba")
assert !"xxx".anagram?("monkey")
# https://twitter.com/crampell/status/238620771398864897
assert "My Ultimate Ayn Rand Porn".anagram?("Mitt Romney and Paul Ryan")
# 1.9 version courtesy of @bheeshmar
class String
def anagram?(other)
raise "Fail!" unless RUBY_VERSION =~ /1.9/
self.downcase.chars.sort == other.downcase.chars.sort
end
end
# 1.9.2p290 :008 > "abc".anagram?("cba")
# => true
# 1.9.2p290 :009 > "abc".anagram?("xxx")
# => false
@randito
Copy link
Author

randito commented Sep 11, 2012

Sorry Bheesh. Doesn't work in 1.8.7.

>> "abc".sort == "cba".sort
=> false

But, a variant does work in 1.9.

class String
  def anagram?(other)
     raise "Fail!" unless RUBY_VERSION =~ /1.9/
     self.downcase.chars.sort == other.downcase.chars.sort
  end
end

1.9.2p290 :008 > "abc".anagram?("cba")
=> true
1.9.2p290 :009 > "abc".anagram?("xxx")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment