66c680f88e8c379fe408d32299dfb4e6

This code outputs whether two strings resolve to being an anagram or not.

I particularly don't like the count_letters method and the checking of the existence of the hash value. Is there a better way?

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')

Refactorings

No refactoring yet !

61f1b34f172ee1fbc1af42ab3ce0eca9

darkleo.myopenid.com

February 19, 2010, February 19, 2010 22:01, permalink

No rating. Login to rate!

and what wrong with reverse ?
"stressed".reverse => "desserts"

D7908f05c89e965f6bc5308ad6f41256

steenslag

February 19, 2010, February 19, 2010 22:45, permalink

No rating. Login to rate!

An anagram is not a palindrome, so the .reverse is not of much use.

class String
  def anagram?(other)
    self.downcase.split(//).sort == other.downcase.split(//).sort
  end
end
puts "dog".anagram?("ogd")
D41d8cd98f00b204e9800998ecf8427e

bob

February 20, 2010, February 20, 2010 02:43, permalink

1 rating. Login to rate!

just sort the chars

class Anagram
  def self.resolves?(first_word, second_word)
    first_word.split('').sort() == second_word.split('').sort()
  end
end

puts Anagram.resolves?('dog','cat')
puts Anagram.resolves?('dog','god')
puts Anagram.resolves?('Jim','Jones')
puts Anagram.resolves?('Hello','olleH')
43f4f7cdf428848d780722c3b01ab460

sdotsen

February 23, 2010, February 23, 2010 14:39, permalink

No rating. Login to rate!

steenslag is correct, what you're looking for is his code. What you are asking for is a palindrome NOT an anagram.

F208f7bab0f04d447b7ed0d7248c4985

stefan

October 5, 2011, October 05, 2011 09:27, permalink

No rating. Login to rate!

what is hello class in anagram

hello class
F208f7bab0f04d447b7ed0d7248c4985

stefan

October 5, 2011, October 05, 2011 09:27, permalink

No rating. Login to rate!

what is hello class in anagram

hello class

Your refactoring





Format Copy from initial code

or Cancel