Sean Sean -4 years ago 62
Ruby Question

Sorting Multiple Directory Entries in Ruby

If I have the following files And they have the following paths (changed for simplicity)

array = ["root_path/dir1/a/file.jpg",
"root_path/dir1/a/file2.jpg",
"root_path/dir1/b/file3.jpg",
"root_path/dir2/c/file4.jpg"]


How can I sort them to get this sort of hash like this?

sort_directory(array)

#=>
{
"dir1" => {
"a" => [
"root_path/dir1/a/file.jpg",
"root_path/dir1/a/file2.jpg"
],
"b" => [
"root_path/dir1/b/file3.jpg"
]
},
"dir2" => {
"c" => [
"root_path/dir2/c/file4.jpg"
]
}
}

Answer Source

one way of doing it using group_by, split and/or some regex

array.group_by{ |dir| dir.split('/')[1] }.map{ |k,v| {k => v.group_by{ |file| file[/\/([^\/]+)(?=\/[^\/]+\/?\Z)/, 1]} } }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download