Adrian Challinor
6/12/2007 6:44:00 AM
rio4ruby wrote:
> On Jun 8, 8:42 pm, Dan Zwell <dzw...@gmail.com> wrote:
>> Michael T. Richter wrote:
>>> On Sat, 2007-09-06 at 11:35 +0900, R.B.Love wrote:
>>>> I've got code working to do what I want but I'm hoping there is a
>>>> better way. Mine seems clumsy.
>>>> My goal is to search over all files, identify all that are directories
>>>> and then do something to each directory. I don't need to go into
>>>> directories recursively yet.
>>>> The fact that Dir.foreach returns strings seems odd to me. All advice
>>>> appreciated.
>>>> #!/usr/local/bin/ruby
>>>> dpath = Dir.getwd
>>>> Dir.foreach(dpath) do
>>>> |x|
>>>> ddir = File.join(dpath,x)
>>>> if File.directory?(ddir) && x != "." && x != ".." then
>>>> puts %x{du -sh #{x}}
>>>> end
>>>> end
>>> Try:
>>> dirs = Dir.entries(".").reject{|e| /\.{1,2}/ =~ e}.find_all{|e|
>>> File.directory? e}
>>> At this point you have a list of directory names. You can do whatever
>>> you like to that list using .each(), .inject(), .collect(), etc.
>> The above has a small bug: it rejects all hidden directories. If you
>> want to block only ".." and ".", then change it to:
>>
>> dirs = Dir.entries(".").reject{|e| /\.{1,2}$/ =~ e}.find_all{|e|
>> File.directory? e}
>
> This also has bug if you have a file name 'abc.'
>
> Use rio.
>
RIO is a great library. It is also a huge library to load for one simple
task. Though it has bugs in it, the author didn't claim that it was the
total solution nor that it didn't leave any holes - but the initial
comment from BB didn't ask for this - BB asked if the original code
worked or was "ugly".
Oh - and hats off to BB. A new person asking for advice on whether their
code is ugly is to be applauded.
What we would need to know is whether BB want to learn the best Ruby way
to do the directory search, or whether they want to do this as a
component in a much larger file processing application. If its the
former, then going with the pure Ruby code is good - and efficient. If
its the latter then RIO is an answer.
For me, the above solution would seem to be more in keeping with "The
Ruby Way".