8

If I have a string array that looks like this:

array = ["STRING1", "STRING05", "STRING20", "STRING4", "STRING3"]

or

array = ["STRING: 1", "STRING: 05", "STRING: 20", "STRING: 4", "STRING: 3"]

How can I sort the array by the number in each string (descending)?

I know that If the array consisted of integers and not strings, I could use:

sort_by { |k, v| -k }

I've searched all around but can't come up with a solution

2
  • Please clarify whether the numbers can have more than a single digit. If 'yes' I suggest you indicate that by simply changing the example to include at least one number greater than 9. If 'no', array.sort_by(&:reverse).reverse also works. Commented Mar 18, 2014 at 1:22
  • Thanks @CarySwoveland! I see what you mean, good to know that works. Commented Mar 18, 2014 at 2:29

2 Answers 2

23

The below would sort by the number in each string and not the string itself

array.sort_by { |x| x[/\d+/].to_i }
=> ["STRING: 1", "STRING: 2", "STRING: 3", "STRING: 4", "STRING: 5"]

descending order:

array.sort_by { |x| -(x[/\d+/].to_i) }
=> ["STRING: 5", "STRING: 4", "STRING: 3", "STRING: 2", "STRING: 1"]
Sign up to request clarification or add additional context in comments.

3 Comments

Remember to convert this to an integer otherwise you'll get unexpected ordering when 1-digit numbers are compared to 2-digit numbers
bjhaid, it's now hard to choose between your answer and @xdazz's. :-)
@CarySwoveland well I did provide the answer with the main idea first (4 minutes earlier than xdazz's) and modification came after the comments, it's the concept behind it that really matters, the remaining changes are obvious, you can check my edit history to confirm that
3

sort the array by the number in each string (descending)

array.sort_by { |x| -x[/\d+/].to_i }

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.