-1

I'm trying to get this to pass spec to verify if an argument is an anagram of another word, but it's just not happening.

  • I can get the string (starting with just one sting word) into an array, and whether it's one or multiple words,
  • It then iterates through the array over each word.
  • Using the If statement to compare if the sorted object is equal to the sorted argument.
  • Applied .join, since it came out one letter at a time in irb, but it's still not happening, with or without .join.

      class String
        define_method(:anagrams) do |check_word|
          words = self.downcase
          check_word = check_word.downcase
          words_array = words.split(" ")
    
          words_array.each do |word|
            if (word.chars.sort) == (check_word.chars.sort)
              true
            else
              false
            end
          end
        end
      end
    

Any ideas why it's broken?

Padawan
  • 724
  • 1
  • 8
  • 20

2 Answers2

1
words_array.each do |word|
  if (word.chars.sort) == (check_word.chars.sort)
    true
  else
    false
  end
end

I'm assuming you want to return true if any words are anagrams. You're currently not explicitly returning.

Better Ruby syntax would be words_array.any? { |word| word.chars.sort == check_word.chars.sort) }

OR

words_array.each do |word|
  return true if (word.chars.sort) == (check_word.chars.sort)
end
Hyung Cho
  • 127
  • 2
0

Here's another way to see if two words w1 and w2 are anagrams of each other:

def anagrams?(w1, w2)
  w1.size == w2.size && w1.chars.difference(w2.chars).empty?
end

where Array#difference is how I defined it in my answer here.

Array#difference is similar to Array#-. The difference is illustrated in the following example:

a = [1,2,3,4,3,2,2,4]
b = [2,3,4,4,4]

a     -      b #=> [1]
a.difference b #=> [1, 3, 2, 2] 

Let's try it:

anagrams?("tops", "stop")  #=> true
anagrams?("tops", "stopz") #=> false
anagrams?("tops", "stopz") #=> false
anagrams?("tops", "sto")   #=> false
Community
  • 1
  • 1
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100