开发者

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 certai开发者_运维百科n 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜