2

I'm trying to sort an array in Ruby by length and alphanumeric:

The desired order would be:

  • site.com?page=7
  • site.com?page=8
  • site.com?page=9
  • site.com?page=880

I've been trying array.sort and sort! but none of them seems to do the trick, as they will place the 880 next after 8.

How would I go about doing this the most effective way?

3 Answers 3

3

Lets say you have an array:

a = ["site.com?page=7", "site.com?page=8", "site.com?page=9", "site.com?page=880"]

Then you can do:

a = a.sort_by{|t| t.split(/page=/)[1].to_i}

In short I use a custom sort criteria and that criteria is to split the string by "page=", then use the numerical value(to_i) of the string after the first match of page= for the sorting.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Though I'm afraid I should have posted the entire URI, as page is just one of many. Is it still possible to do something?
1

You can use the group_by function to group items by length and sort_by to order them alphanumerically within the group, and finally flatten the groups:

list.group_by {|i| i.length}.sort_by{|i| i.first}.collect {|i| i.last.sort}.flatten

Comments

0

A general trick is to zero pad the numbers using a fixed number of decimal places before sorting the array strings.

This can be easily accomplished by the following code:

a = ["site.com?page=9","site.com?page=880""site.com?page=8","site.com?page=7"]

N = 5  # Maximum number of decimal places allowed

a.sort_by { |s| s.gsub(/(\d+)/) { |n| sprintf("%0#{N}d", n.to_i) } }

This works well unless the strings contain any number greater than or equal to 10^N.

Comments

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.