Help on a script

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

exclude . and … in directories

elsif File.directory?(f) && File.basename(f) != ‘…’ && File.basename(f)
!=
‘.’

Maybe like this? :frowning:

Ruby N. wrote:

        open(f) do |c|

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

Thanks all.
Under all your helps, I finally get the script to work correctly.

def myfind(path=".")
Dir.foreach(path) do |f|
f = File.join(path,f)

puts f

    if File.file? f
        open(f) do |c|
            puts "#{f}" unless c.read.scan(/ruby/).empty?
        end
    elsif File.directory? f and File.basename(f) != "." and

File.basename(f) != “…”
myfind(f)
end
end
end

myfind

Thanks.
Jenn.

2010/1/20 Ruby N. [email protected]:

Thanks all.
Under all your helps, I finally get the script to work correctly.

def myfind(path=“.”)
Dir.foreach(path) do |f|
f = File.join(path,f)

puts f

   if File.file? f
       open(f) do |c|
           puts "#{f}" unless c.read.scan(/ruby/).empty?

You just need a single match - not all of them.

       end
   elsif File.directory? f and File.basename(f) != "." and

File.basename(f) != “…”
myfind(f)
end
end
end

myfind

It is easier if you use Find:

require ‘find’

Find.find path do |f|
puts f if File.file?(f) && /ruby/ =~ File.read(f)
end

:slight_smile:

http://www.ruby-doc.org/stdlib/libdoc/find/rdoc/index.html

Kind regards

robert