Page 1 of 1

Sorting File paths

Posted: Wed Oct 05, 2016 12:36 am
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!

Re: Sorting File paths

Posted: Wed Oct 05, 2016 9:30 am
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

Re: Sorting File paths

Posted: Wed Oct 05, 2016 12:18 pm
by adamszabo
Ah thank you, just what I was looking for! :mrgreen: