2

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
dbenhur
  • 20,008
  • 4
  • 48
  • 45
nprs
  • 93
  • 1
  • 6

2 Answers2

2

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.

squiguy
  • 32,370
  • 6
  • 56
  • 63
  • Thank you . Appreciate your answer . This is exactly what I was trying to accomplish . Thanks for the insight into f.first and File.join – nprs Apr 12 '13 at 04:08
2

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 }
dbenhur
  • 20,008
  • 4
  • 48
  • 45
  • This is quite an interesting approach, it made me think for a while. – squiguy Apr 11 '13 at 23:52
  • @squiguy The idea is not to make you think, but to say what you want plainly. Once you're used to thinking/reading in the more functional style, this just reads like a recipe: 1) produce directory list, 2) map names to paths, 3) select those that are files, 4) print the first line of each file. – dbenhur Apr 12 '13 at 00:02
  • I'm not against functional styles, I just appreciate it :). – squiguy Apr 12 '13 at 00:16
  • Thanks for your help and explaining the code. As you can seeI'm newbie to ruby . Thanks again! – nprs Apr 12 '13 at 04:05