Reputation: 225
I have the following array...
[ "global/20130102-001", "global/20131012-001, "country/uk/20121104-001" ]
I need to sort the array based on the numerical portion of the string. So the above would be sorted as:
[ "country/uk/20121104-001", "global/20130102-001", "global/20130112-001 ]
Is there a way to call .sort and ignore the first part of each element so I'm only sorting on the number?
Upvotes: 1
Views: 1619
Reputation: 230551
Yes, there's a way. You should use a #sort_by
for that. Its block is passed an array element and should return element's "sortable value". In this case, we use regex to find your string of digits (you can use another logic there, of course, like splitting on a slash).
arr = [ "global/20130102-001", "global/20131012-001", "country/uk/20121104-001" ]
arr.sort_by {|el| el.scan(/\d{8}-\d{3}/)} # => ["country/uk/20121104-001", "global/20130102-001", "global/20131012-001"]
Upvotes: 4