user1074981
user1074981

Reputation: 225

Sorting a Ruby array based on part of a string

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

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

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

Faiz
Faiz

Reputation: 16265

Sure, just use sort_by.

  arr.sort_by do |s| 
     s.split('/').last
  end

Upvotes: 6

Related Questions