0

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

0

2 Answers 2

3

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

This solution is great because the word "regional" is not hard coded into the method. The directory name could be anything as long as the relative path of the script t the files doesnt change. Thanks
1

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"]

3 Comments

what is the output OP is looking for,I didn't get that. Could you help me out on that ? :(
Just added the output I think he is looking for ;)
Yeah! I just seen.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.