banditKing
banditKing

Reputation: 9579

Extract the filepath from this ruby string

I am using the ruby Dir method to get all the filenames within a directory. Like this:

 dir_files = Dir["/Users/AM/Desktop/07/week1/dailies/regionals/*.csv"]

This gives me an array with each element listed below:

 /Users/AM/Desktop/07/week1/dailies/regionals/ch002.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch014.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch90.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch112.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch234.csv

Im trying to extract just the part of the above strings that matches: "regionals/*.csv"

How do I do that in Ruby?

The following didn't work

@files_array.each do |f|
     f = f.split("/").match(/*.csv/)
    i = f.include?(".csv")
    puts "#{i.inspect}"

    #self.process_file(f[i])
 end

Whats a clever way of doing this? I intend to pass the returned string of each filename to a helper method for processing. But as you can see all the csv files are located in a different directory as my executing script. My script thats executing this is located at

 /Users/AM/Desktop/07/week1/dailies/myScript.rb

Thanks

Upvotes: 0

Views: 115

Answers (2)

apiology
apiology

Reputation: 66

This will always post back the final directory and file name, regardless of the file pattern:

@files_array.map { |f| f.split("/")[-2..-1].join("/") }
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]

Upvotes: 3

tessi
tessi

Reputation: 13574

This gives you the desired values :)

dir_files.map {|path| path[/regionals\/.*.csv/]}
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]

Upvotes: 1

Related Questions