1

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?

1
  • Which numerical portion? The first? The second? The combination of both? Commented Jan 23, 2013 at 6:38

2 Answers 2

6

Sure, just use sort_by.

  arr.sort_by do |s| 
     s.split('/').last
  end
Sign up to request clarification or add additional context in comments.

Comments

4

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"]

3 Comments

This looks great but unfortunately I'm using v1.8.7
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: well, use sort_by, not sort_by!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.