How to read files from a directory foreach?


(Kurt Euler) #1

All-

Is there a way to use some type of foreach loop to read in each text file in a directory, each pass returning a file name and its contents in two separate strings, until all files have been read?

I believe there is a command that reads all file names in a directory into an array. However, I’d rather see if there’s a quick and dirty way to step through each file without creating (and then working with) such array.

Thanks.

-Kurt Euler


(Ned Konz) #2

Dir.new(‘dirname’).each { |fname|
if File.file? fname
File.open(fname) { |file|
contents = file.read
# do something with contents
}
end
}

···

On Tuesday 11 June 2002 10:08 pm, Kurt Euler wrote:

Is there a way to use some type of foreach loop to read in each
text file in a directory, each pass returning a file name and its
contents in two separate strings, until all files have been read?


Ned Konz
http://bike-nomad.com
GPG key ID: BEEA7EFE


(Yohanes Santoso) #3

Kurt Euler keuler@portal.com writes:

All-

Is there a way to use some type of foreach loop to read in each text
file in a directory, each pass returning a file name and its
contents in two separate strings, until all files have been read?

How about a 3-liner?

hash={}
Dir.entries(".").each{ |file| File.open(file) {|fh| hash[file] = fh.readlines.to_s} if File.stat(file).file? }
array=hash.to_a # => array[0][0] = filename, array[0][1] = content

I believe there is a command that reads all file names in a
directory into an array. However, I’d rather see if there’s a quick
and dirty way to step through each file without creating (and then
working with) such array.

See above.

YS.


(Park Heesob) #4

“Yohanes Santoso” ruby-talk@jenny-gnome.dyndns.org wrote in message
news:87ptyx1218.fsf@jenny-gnome.dyndns.org

Kurt Euler keuler@portal.com writes:

All-

Is there a way to use some type of foreach loop to read in each text
file in a directory, each pass returning a file name and its
contents in two separate strings, until all files have been read?

How about a 3-liner?

hash={}
Dir.entries(".").each{ |file| File.open(file) {|fh| hash[file] =
fh.readlines.to_s} if File.stat(file).file? }
array=hash.to_a # => array[0][0] = filename, array[0][1] = content

How about 1-liner?

array = Dir["."].find_all{|x| File.file? x}.collect {|fn| [fn,File.open(fn)
{ |f| f.read }] }

Park Heesob.