Ruby Dir.glob alternative with Regexp
Asked Answered
A

2

7

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?

Aristotelianism answered 20/8, 2015 at 18:5 Comment(3)
You may be able to use Find to walk directories and do a regex against them [?] https://mcmap.net/q/491840/-what-39-s-the-ruby-equivalent-of-python-39-s-os-walkPaleozoology
The documentation says it clearly: "Note that this pattern is not a regexp, it's closer to a shell glob." Consider it like you would a pattern to a ls at the command-line.Antineutrino
Find is an excellent, though underused, way to walk a directory hierarchy. Using regexp with Dir and Find is easy done using select and reject to find matches, or within blocks using next or prune.Antineutrino
A
12

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"]
Aylsworth answered 20/8, 2015 at 18:18 Comment(0)
A
3

Although full regex isn't supported, you can do tricks like the following in glob

Dir.glob("folder_with_images/*.{jpg,png}")
Arduous answered 11/4, 2019 at 7:49 Comment(1)
I used this to do Dir.glob("test/models/#{model}{/*_test.rb,_test.rb} to find test/model/abc_test.rb as well as test/model/abc/my_sub_test.rbPointless

© 2022 - 2024 — McMap. All rights reserved.