Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...