简体   繁体   中英

Advanced Array Sorting in Ruby

I'm currently working on a project in ruby, and I hit a wall on how I should proceed. In the project I'm using Dir.glob to search a directory and all of its subdirectories for certain file types and placing them into an arrays. The type of files I'm working with all have the same file name and are differentiated by their extensions. For example,

txt_files = Dir.glob("**/*.txt")
doc_files = Dir.glob("**/*.doc")
rtf_files = Dir.glob("**/*.rtf")

Would return something similar to,

FILECON.txt ASSORTED.txt FIRST.txt

FILECON.doc ASSORTED.doc FIRST.doc

FILECON.rtf ASSORTED.rtf FIRST.rtf

So, the question I have is how I could break down these arrays efficiently (dealing with thousands of files) and placing all files with the same filename into an array. The new array would look like,

FILECON.txt FILECON.doc FILECON.rtf

ASSORTED.txt ASSORTED.doc ASSORTED.rtf

etc. etc.

I'm not even sure if glob would be the correct way to do this (all the files with the same file name are in the same folders). Any help would be greatly appreciated!

Get all your files into a single array with Dir.glob("**/*.{txt,doc,rtf}")

Don't forget that all the filenames have the directory too, so if you want to sort by the basename, then

files = Dir.glob("**/*.{txt,doc,rtf}").sort_by {|f| File.basename f}

Not sure if this is exactly what you need, but you can try to

# first get all files
all_files = Dir.glob('**/*')
# then you can group them by name
by_name = all_files.group_by{|f| m = f.match(/([^\/]+)\.[^.\/]+$/); m[1] if m}
# and by extension
by_ext = all_files.group_by{|f| m = f.match(/[^\/]+\.([^.\/]+)$/); m[1] if m}

BTW, I don't see any relation of the question with sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM