Forum: Ruby Loop through files in a directory

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
328f0bb678423fcea01ebe3b0edc74e6?d=identicon&s=25 Ben Johnson (benjohnson)
on 2007-05-04 22:40
I know this is a nub question, but the documentation on ruby is
terrible.

How do I loop through all of the files in a directory?

Thanks for your help.
97550977337c9f0a0e1a9553e55bfaa0?d=identicon&s=25 Jano Svitok (Guest)
on 2007-05-04 22:48
(Received via mailing list)
On 5/4/07, Ben Johnson <bjohnson@mediamanifest.com> wrote:
> I know this is a nub question, but the documentation on ruby is
> terrible.
>
> How do I loop through all of the files in a directory?
>
> Thanks for your help.
>
> --
> Posted via http://www.ruby-forum.com/.

Have a look at Find.find and Dir.each.
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2007-05-04 23:51
(Received via mailing list)
On Sat, 5 May 2007, Ben Johnson wrote:

> I know this is a nub question, but the documentation on ruby is
> terrible.
>
> How do I loop through all of the files in a directory?
>
> Thanks for your help.
>
> --
> Posted via http://www.ruby-forum.com/.
>


   harp:~ > ls dir
   a  b  c


   harp:~ > cat a.rb
   class Dir
     def self.ls dir, glob = File.join('**', '**'), &block
       ret = [] unless block
       Dir.glob(File.join(dir, glob)) do |entry|
         block ? block.call(entry) : ret.push(entry)
       end
       ret
     end
   end

   Dir.ls 'dir' do |entry|
     puts entry
   end

   entries = Dir.ls 'dir'
   p entries


   harp:~ > ruby a.rb
   dir/a
   dir/b
   dir/c
   ["dir/a", "dir/b", "dir/c"]

-a
Ce5990549a8185ad45643be2cfbff9b5?d=identicon&s=25 Mike Steiner (Guest)
on 2007-05-05 01:01
(Received via mailing list)
def GetRecursiveFileList ( dirname )
    results = Array.new
    # both methods should work the same (I think one returns the
directory
names in addition to the files)
    use_method = 0
    if use_method == 0
        Dir["#{dirname}/**/**"].each do | thisfile |
            thisfile.gsub! ( /\// , '\\' )
            results.push ( thisfile )
        end
    else
        require 'find'
        Find.find ( dirname ) do | thisfile |
            thisfile.gsub! ( /\// , '\\' )
            results.push ( thisfile )
        end
    end
    return results
end
This topic is locked and can not be replied to.