Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Dir.glob alternative with Regexp

Ruby's Dir.glob accepts a glob String that has some regular expression behaviour, but it doesn't have the full abilities of Regexp.

What alternatives in Ruby (including core and gems) are there to Dir.glob that allow the use of Regexp to match file paths?

like image 370
Eliot Sykes Avatar asked Aug 20 '15 18:08

Eliot Sykes


1 Answers

The thing with glob is that it can match subpaths. When you write Dir.glob('*/*') it'll return all the files and directories directly under subdirectories of the current directories. It can do that because glob patterns are simple enough for the computer to understand - if it was regex it would have to scan the entire filesystem and compare each path with the pattern, which is simply too much.

However, you can combine - use Dir.glob to choose where to search, and grep to choose what to search:

[1] pry(main)> Dir.glob('/usr/lib/*').grep(/\/lib[A-Z]+\.so$/)
=> ["/usr/lib/libFLAC.so", "/usr/lib/libEGL.so", "/usr/lib/libHACD.so", "/usr/lib/libLTO.so", "/usr/lib/libGLEW.so", "/usr/lib/libGL.so", "/usr/lib/libSDL.so", "/usr/lib/libGLU.so", "/usr/lib/libSM.so", "/usr/lib/libICE.so"]
like image 61
Idan Arye Avatar answered Oct 06 '22 22:10

Idan Arye