How to read files from a directory foreach?


(Kurt Euler) #1

Thanks all!

···

-----Original Message-----
From: Park Heesob [mailto:phasis@kornet.net]
Sent: Tuesday, June 11, 2002 11:22 PM
To: ruby-talk@ruby-lang.org
Subject: Re: How to read files from a directory foreach?

“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.