Robert Klemme
9/21/2006 10:08:00 AM
On 21.09.2006 11:06, Newbie wrote:
> def traverse(root)
> Dir.foreach(root) do |file|
> next if file[0] == ?.
> puts file
> traverse(root + '\\' + file) if File.directory?(root + '\\' + file)
> end
> end
>
> This is my initial attempt. Two things feel rather wrong:
> 1) Is there a simpler way to test the beginning of a string? A
> startsWith?(aString) like method?
Like this?
next if /^\./ =~ file
> 2) I'm iterating through filenames, then appending the path each time.
> Is there a way to get a collection of File objects from a directory?
File objects are for actually reading and writing objects. You can do
Dir["*"] which returns an array of strings.
> Any other pointers to where I could improve would also be greatly
> appreciated.
Use Find:
irb(main):001:0> require 'find'
=> true
irb(main):002:0> Find.find('.') {|f| puts f}
.
../x
../prj-jar.txt
../jdk-jar.txt
=> nil
irb(main):005:0> Find.find('/tmp') {|f| puts f}
/tmp
/tmp/x
/tmp/prj-jar.txt
/tmp/jdk-jar.txt
=> nil
irb(main):008:0> Find.find '/tmp' do |f|
irb(main):009:1* next if File.directory? f
irb(main):010:1> puts f
irb(main):011:1> end
/tmp/x
/tmp/prj-jar.txt
/tmp/jdk-jar.txt
Note, you can also use File.join to portably combine paths.
Kind regards
robert