Your code is not idiomatic Ruby. I'd write it something like this untested code:
Dir.chdir(File.dirname(__FILE__))
puts 'Enter file name: '
rel_path = gets.chomp
abs_path = File.absolute_path(rel_path)
if File.exist?(abs_path)
puts 'File exists'
File.foreach(abs_path) do |line|
# process the line
end
else
puts 'File does not exist'
end
While Ruby supports the use of ;
, they're for use when we absolutely must provide multiple commands on one line. The ONLY time I can think of needing that is when using Ruby to execute single-line commands at the command-line. In normal scripts I've never needed ;
between statements.
then
is used with if
when we're using a single line if
expression, however, we have trailing if
which removes the need for then
. For instance, these accomplish the same thing but the second is idiomatic, shorter, less verbose and easier to read:
if true then a = 1 end
a = 1 if true
See "What is the difference between "if" statements with "then" at the end?" for more information.
Instead of relPath
and absPath
we use snake_case for variables, so use rel_path
and abs_path
. It_is_a_readability AndMaintenanceThing.
File.absolute_path(rel_path)
is a good way to take the starting directory and return the absolute path given a relative directory.
File.foreach
is a very fast way to read a file, faster than slurping it using something like File.read
. It is also scalable whereas File.read
is not.