Panepickosci Panepickosci - 6 months ago 37
Ruby Question

Ruby palindrome words in a text file

I am trying to write a ruby program which is going to find and display the palindrome words saved in a file example: (c:/palindrome.txt). I was trying to find solution on how to use the palindrome in that case, but I could not get expected results.
So basically I was thinking to put everything from the file into a string first and the somehow check and display palindrome words. This is the part I get confused. I simply do not know how to do that.

@string=""
File.new("C:\\palindrome.txt", "r").each do |line|
@string += line
end


I am not sure if I can use conditions when it is about palindrome, is there a specific function for that? So it would be something like if word is a palindrome then print it.

Answer

This will work

words = File.read("c:/palindrome.txt")
words_array = words.downcase.split(" ")

palindromes = []

words_array.each do |word|
    if word.length>1
        palindromes << word if word == word.reverse
    end
end

puts palindromes