Support

If you have a problem or need to report a bug please email : support@dsprobotics.com

There are 3 sections to this support area:

DOWNLOADS: access to product manuals, support files and drivers

HELP & INFORMATION: tutorials and example files for learning or finding pre-made modules for your projects

USER FORUMS: meet with other users and exchange ideas, you can also get help and assistance here

NEW REGISTRATIONS - please contact us if you wish to register on the forum

Users are reminded of the forum rules they sign up to which prohibits any activity that violates any laws including posting material covered by copyright

Sorting File paths

For general discussion related FlowStone

Sorting File paths

Postby adamszabo » Wed Oct 05, 2016 12:36 am

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!
adamszabo
 
Posts: 667
Joined: Sun Jul 11, 2010 7:21 am

Re: Sorting File paths

Postby tulamide » Wed Oct 05, 2016 9:30 am

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 804 times
"There lies the dog buried" (German saying translated literally)
tulamide
 
Posts: 2714
Joined: Sat Jun 21, 2014 2:48 pm
Location: Germany

Re: Sorting File paths

Postby adamszabo » Wed Oct 05, 2016 12:18 pm

Ah thank you, just what I was looking for! :mrgreen:
adamszabo
 
Posts: 667
Joined: Sun Jul 11, 2010 7:21 am


Return to General

Who is online

Users browsing this forum: No registered users and 76 guests