Sorting File paths

For general discussion related FlowStone
Post Reply
adamszabo
Posts: 667
Joined: Sun Jul 11, 2010 7:21 am

Sorting File paths

Post by adamszabo »

Hey guys, i've been scratching my head over this one. Lets say I have an array containing some file paths:

Folder/1.txt
Folder/23.txt
Folder/6.txt
Folder/Piano.txt
Folder/Wave01.txt
Folder/Wave02.txt
Zebra/1.txt
Zebra/76.txt
Zebra/9.txt

Now when ruby gets these paths it looks different from windows. Ruby thinks 23 comes after 1 because it starts with a 2, but they should be numerically higher, like this:

Folder/1.txt
Folder/6.txt
Folder/23.txt
Folder/Piano.txt
Folder/Wave01.txt
Folder/Wave02.txt
Zebra/1.txt
Zebra/9.txt
Zebra/76.txt

Is there a way to sory them by using the .sort_by function or something else?

Thank you!
tulamide
Posts: 2714
Joined: Sat Jun 21, 2014 2:48 pm
Location: Germany

Re: Sorting File paths

Post by tulamide »

What you are looking for is called "natural sort". I found a conversation on StackOverflow here, and made a quick fsm. It isn't bullet-proof! If any of your strings start with a number it will result in an error. However, if your strings are like in your example, it works.

To make this work in your project, you have to make sure that this code is initialized before you access it:

Code: Select all

class String
  def naturalized
    scan(/[^\d]+|[\d]+/).collect { |w| w.match(/\d+/) ? w.to_i : w }
  end
end
Attachments
natural_sort_2.fsm
(434 Bytes) Downloaded 864 times
"There lies the dog buried" (German saying translated literally)
adamszabo
Posts: 667
Joined: Sun Jul 11, 2010 7:21 am

Re: Sorting File paths

Post by adamszabo »

Ah thank you, just what I was looking for! :mrgreen:
Post Reply