Reputation: 8588
I need to get extract a filename from within my project with Ruby and extract the first word from it. I have tried it with a solution I found here on this site, but without success:
File.basename("/path/to/folder/here_is_my_file.rb").match(/[^_]+/)
this returns => "here" as expected.
What I need, however, is to fetch "here" without knowing what it is supposed to be, since the first part of the filename is dynamically generated. Therefore I need to find a way to extract it dynamically.
How can that be achieved?
Upvotes: 2
Views: 990
Reputation: 13014
What you need is to find the files on your path which match the pattern *_file.rb
.
To do that, use the globbing from Dir
class in Ruby.
matched_files = Dir['/path/to/folder/*_file.rb']
#=> ['/path/to/folder/main_file.rb', '/path/to/folder/sub_file.rb', '/path/to/folder/foo_file.rb']
Now, you can extract the basename by iterating over those files:
base_files = matched_files.map { |file| File.basename(file) }
#=> ['main_file.rb', 'sub_file.rb', 'foo_file.rb']
Additionally, if you just want to extract main, sub, foo from that, you can match against the pattern to do that as:
base_files.map { |file| file.match(/(.*)_file.rb/)[1] }
#=> ['main', 'sub', 'foo']
With the files name collected, you can check those names against your conditionals to execute whatever is meant for that file..
Good luck.
Upvotes: 1