0

Is there any way in Ruby where I can do a global search for a given file?

I tried Dir.glob but it searches in the current directory. And for the Find module I need to pass a list of directories to search. In my case, I need to search for a particular file which might be in any directory.

How can I do this in Ruby?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
rajkumarts
  • 399
  • 1
  • 7
  • 20
  • Please define "global" – Stefan Dec 15 '14 at 16:52
  • to look for a file in my users computer.. – rajkumarts Dec 15 '14 at 16:55
  • 2
    While Ruby *can* do this, it's nowhere near the best tool available. You don't say what OS you're on, but *nix has `locate` and `find`. The first relies on a database that is periodically refreshed so it contains current information about what files are on the disk, and, as a result, is very fast. `find` iteratively searches directory hierarchies and can be told to find files with specific names or attributes. It's fast, but because it's walking the drive it's a lot slower. Either is faster than what Ruby can do, but are not as flexible as code you write. – the Tin Man Dec 15 '14 at 17:15

2 Answers2

2

Find recurses into subdirectories, so just start at the root path, it'll go everywhere:

Find.find('/') do |path|
  # look for your filename
end
Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • 2
    And [`Dir.glob('/**/some_file')`](http://www.ruby-doc.org/core-2.1.5/Dir.html#method-c-glob) will eventually find it. On a big disk either could seek a long time. – the Tin Man Dec 15 '14 at 17:19
  • @theTinMan yea i added that in my block and tested. And as you mentioned in your comment, I find it slow. I am currently looking into narrowing down to a particular directories to make it more fast. Thanks for your input. – rajkumarts Dec 15 '14 at 17:22
  • 1
    The best thing to do is write several different ways of accomplishing the same thing, including using `find` and `locate`, and run benchmarks to test the speed of each. You're trading off flexibility vs. speed and the more you can tell the Ruby code about its search path the faster it will be, but at no time will it be as fast as the OS tools. – the Tin Man Dec 15 '14 at 17:29
1

On systems that have the locate command line tool, like Linux and Mac OSX, you can find files very fast like this:

filename = "test"
array_of_files_found = `locate #{filename}`.split("\n")

Be aware of the dangers of passing user-supplied parameters to the command line. See this answer for details

Also note that on OSX, you might need to create the database that powers the locate command like this:

sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
Community
  • 1
  • 1
monkbroc
  • 808
  • 9
  • 13