Skip to content

Instantly share code, notes, and snippets.

@imtiaz-emu
Created October 28, 2018 05:07
Show Gist options
  • Save imtiaz-emu/955a107982e8502694f3b5824addc989 to your computer and use it in GitHub Desktop.
Save imtiaz-emu/955a107982e8502694f3b5824addc989 to your computer and use it in GitHub Desktop.
Inside the file "http://tech2.bumbung.net/questions/words.txt" is a list of words that we would like to test whether each word is a palindrome.
# I/O file location
file_path = "/home/emu/RubyProjects/Bumbung/words.txt" # words.txt file downloaded from the question link
output_path = "/home/emu/RubyProjects/Bumbung/palindrome.txt"
# read words from file
File.open(file_path, "r") do |f|
f.each_line do |line|
# remove punctuations from word, then downcase word to ignore case
str = line.gsub(/[^a-zA-Z0-9\-]/,"").downcase
# if original downcase string and reversed string are same
# then its a palindrome, otherwise not
# write output on the file (create output file if not exists)
if(str == str.reverse)
File.open(output_path, 'a') {|f| f.write("palindrome\n") }
else
File.open(output_path, 'a') {|f| f.write("not_palindrome\n") }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment