Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Can't get Ruby method to pass spec for Anagram method

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

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

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...