Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Which numerical portion? The first? The second? The combination of both? –  sawa Jan 23 '13 at 6:38

2 Answers 2

up vote 2 down vote accepted

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"]
share|improve this answer
    
This looks great but unfortunately I'm using v1.8.7 –  user1074981 Jan 23 '13 at 5:12
    
I just tested it, and this works on Ruby 1.8.7. –  the Tin Man Jan 23 '13 at 5:15
    
I get undefined method `sort_by!' for #<Array:0x7f7c81762410> (NoMethodError). There's no sort_by! method in the ruby doc ruby-doc.org/core-1.8.7/Array.html –  user1074981 Jan 23 '13 at 5:22
    
@user1074981: well, use sort_by, not sort_by! –  Sergio Tulentsev Jan 23 '13 at 5:23

Sure, just use sort_by.

  arr.sort_by do |s| 
     s.split('/').last
  end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.