tags:

views:

540

answers:

4

How do i write a loop in ruby so that I can execute a block of code on each file?

I'm new to ruby, and I've concluded that the way to do this is a do each loop.

The ruby file will be executed from a different directory than the directory I want to loop through.

I've tried the Dir.foreach and I couldn't get it to work.

+5  A: 
Dir.foreach("/home/mydir") do |fname|
  puts fname
end
Fred
Alternatively use Dir#[] or Dir#glob
Ryan Bigg
+2  A: 
Dir.new('/my/dir').each do |name|
  ...
end
invariant
In addition to Dir.new('/my/dir') there's also Dir.entries('/my/dir') but Dir.foreach() is a bit more succinct.
Greg
@Z.E.D. Also `Dir.foreach` iterates while `Dir.entries` builds the whole array up at once. So if the directory is immense, it's less of a memory hit. (Not usually a big deal, probably, but still...)
Telemachus
+6  A: 

As others have said, Dir.foreach is a good option here. However, note that Dir.entries and Dir.foreach will always show . and .. (the current and parent directories). You will generally not want to work on them, so you can do something like this:

Dir.foreach('/path/to/dir') do |item|
  next if item == '.' or item == '..'
  # do work on real items
end

Dir.foreach and Dir.entries also show all items in the directory - hidden and non-hidden alike. Often this is what you want, but if it isn't, you need to do something to skip over the hidden files and directories.

Alternatively, you might want to look into Dir.glob which provides simple wildcard matching:

Dir.glob('/path/to/dir/*.rb') do |rb_file|
  # do work on files ending in .rb in the desired directory
end
Telemachus
A: 

The find library is designed for this task specifically: http://stdlib.rubyonrails.org/libdoc/find/rdoc/index.html

require 'find'
Find.find(path) do |file|
  # process
end

This is a standard ruby library, so it should be available

Faisal
`File.find` goes recursively down as far as it can, starting from whatever path you give it. I'm not sure that is what the OP wants.
Telemachus