Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Using a regular expression to find and open a file based on its filename?

I am trying to test the contents of a file that is generated from code. The problem is that the full name of the file is based on a timestamp abc123_#{d.strftime('%Y%m%d%I%M%S')}.log

How could I use File to find this file and read it? I tried doing File.exists?() with a regular expression as the parameter but that didn't work.

I found this in another question on stackoverflow:

File.basename(file_path).match(/_.*(css|scss|sass)/)

How would I be able to use that in my case where the file is located in mypublic folder?

ANSWER

So the two answers below both work and I used a combination of them.

Dir['public/*.log'].select { |f| f =~ /purge_cc_website/}

The * acts as a wildcard that is sort of a regular expression in itself. After that you filter the array using an actual regex.

like image 776
bigpotato Avatar asked Jun 11 '13 19:06

bigpotato


1 Answers

Dir[] takes a file glob so, if your pattern isn't too complicated, you can just do:

Dir['public/abc123_*.log']

More glob info here.

like image 106
Bob Briski Avatar answered Sep 27 '22 19:09

Bob Briski