This is basically my first Ruby class, which is to remove all empty lines and blank times from a .txt file. A simple test case is also included.
I tested the code and it works fine. But I did not have much idea about if the code style is good, or if there are some potential issues. Can someone please do a quick review and kindly provide some feedback?
Is there any potential issue in the code? did I miss some boundary check?
Is the code style good in general? e.g, name convention, indent, etc.
what can I do if I want to make it more professional? e.g., better choice of functions, error-handling, object-oriented, test-driven, etc.
require 'test/unit'
class BlankLineRemover
def initialize()
puts "BlankLineRemover initialized."
end
def generate(input_filename, output_filename)
reader = File.read(input_filename)
f = File.new(output_filename, "w")
f.puts remove(reader)
f.close
end
def remove(stringToremove)
regEx = /^[\s]*$\n/
stringToReturn = stringToremove.gsub(regEx, '')
stringToReturn.strip!
if stringToReturn.length >= 1
return stringToReturn
else
return ""
end
end
end
class TestCleaner < Test::Unit::TestCase
def test_basic
sInput1 = "line1\n\t\nline4\n\tline5\n"
sExpectedOutput1 = "line1\nline4\n\tline5"
sInput2=""
sExpectedOutput2 = ""
sInput3="\n\t\t\n"
sExpectedOutput3 = ""
testCleaner = BlankLineRemover.new
assert_equal(sExpectedOutput1, testCleaner.remove(sInput1))
assert_equal(sExpectedOutput2, testCleaner.remove(sInput2))
assert_equal(sExpectedOutput3, testCleaner.remove(sInput3))
end
end
unless ARGV.length == 2
puts "Usage: ruby Blanker.rb input.txt output.txt\n"
exit
end
simpleRemover = BlankLineRemover.new
simpleRemover.generate(ARGV[0],ARGV[1])
remove
you have anif/else
that could be re-written asstringToReturn.length >= 1 ? stringToReturn : ""
, but to check that a string has a size bigger than one you're better of with!stringToReturn.empty?
but then again the only way to fall on thatelse
is ifstringToReturn
is an empty string (which is the return value of the else) and therefore you don't need thatif/else
at all and simply letstringToReturn.strip!
be the return value of that method. \$\endgroup\$