From: Ammar Ali Date: 2010-01-20T18:38:37+09:00 Subject: Re: help on a script Ruby Newbee wrote: > Hi, > > I just wrote a small script to find the files in current directory and > its child directories which include the word "ruby". > But it can't work, please help point out my error, thanks. > > > def myfind(path=".") > Dir.foreach(path) do |f| > if File.file? f > open(f) do |c| > puts "#{path}/#{f}" if c.read.scan(/ruby/) > end > elsif File.directory? f > newpath = File.join path,f > myfind(newpath) > end > end > end > > myfind > > > Hi, Walking the directory recursively can be done with 'glob', or it's equivalent method '[]'. The following will recursively find all files that have a '.rb' extension, starting from the current directory. Dir['**/*.rb'].each { |path| puts path } The scan method returns an array of matches, or takes a block which can act on that array. To check if any matches where found, one can check that the returned array is not empty, for example: puts path if c.read.scan(/ruby/).length > 0 ammar