Question

Below is the piece of code that is supposed read the directory and for each file entry prints the first row of the file. The issue is x is not visible so file is not being parsed.

Dir.foreach("C:/fileload/src") do |file_name|
  x = file_name
  puts x
  f = File.open("C:/fileload/src/" +x)
  f.readlines[1..1].each do |line| 
    puts line 
  end
end
Was it helpful?

Solution

Why are you assigning x to file_name? You can use file_name directly. And if you are only reading the first line of the file, why not try this?

#!/usr/bin/ruby

dir = "C:/fileload/src"
Dir.foreach(dir) do |file_name|
    full = File.join(dir, file_name)
    if File.file?(full)
        f = File.open(full)
        puts f.first
        f.close
    end
end

You should use File.join to safely combine paths in Ruby. I also checked that you are opening a file using the File.file? method.

OTHER TIPS

You have no visibility issue with x. You should be using File::join or Pathname#+ to build your file paths. You should exclude non-files from consideration. You're selecting the second line, not the first with [1..1]. Here's a cleaner correct replacement for your sample code.

dir = "C:/fileload/src"
Dir.foreach(dir).
map    { |fn| File.join(dir,fn) }.
select { |fn| File.file?(fn) }.
each   { |fn| puts File.readlines(fn).first }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top