Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6376435
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T01:44:41+00:00 2026-05-25T01:44:41+00:00

There are workable answers for sorting an array of hashes and for natural sorting

  • 0

There are workable answers for sorting an array of hashes and for natural sorting, but what is the best way to do both at once?

my_array = [ {"id":"some-server-1","foo":"bar"},{"id":"some-server-2","foo":"bat"},{"id":"some-server-10","foo":"baz"} ]

I would like to sort on “id” such that the final ordering is:

some-server-1
some-server-2
some-server-10

I feel like there must be a clever and efficient way to do this, though personally I don’t need to break any speed records and will only be sorting a few hundred items. Can I implement a comparison function in sort_by?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T01:44:42+00:00Added an answer on May 25, 2026 at 1:44 am

    First of all, your my_array is JavaScript/JSON so I’ll assume that you really have this:

    my_array = [
        {"id" => "some-server-1",  "foo" => "bar"},
        {"id" => "some-server-2",  "foo" => "bat"},
        {"id" => "some-server-10", "foo" => "baz"}
    ]
    

    Then you just need to sort_by the numeric suffix of the 'id' values:

    my_array.sort_by { |e| e['id'].sub(/^some-server-/, '').to_i }
    

    If the “some-server-” prefixes aren’t always “some-server-” then you could try something like this:

    my_array.sort_by { |e| e['id'].scan(/\D+|\d+/).map { |x| x =~ /\d/ ? x.to_i : x } }
    

    That would split the 'id' values into numeric and non-numeric pieces, convert the numeric pieces to integers, and then compare the mixed string/integers arrays using the Array <=> operator (which compares component-wise); this will work as long as the numeric and non-numeric components always match up. This approach would handle this:

    my_array = [
        {"id" => "some-server-1", "foo" => "bar"},
        {"id" => "xxx-10",        "foo" => "baz"}
    ]
    

    but not this:

    my_array = [
        {"id" => "11-pancakes-23", "foo" => "baz"},
        {"id" => "some-server-1",  "foo" => "bar"}
    ]
    

    If you need to handle this last case then you’d need to compare the arrays entry-by-entry by hand and adjust the comparison based on what you have. You could still get some of the advantages of the sort_by Schwartzian Transform with something like this (not very well tested code):

    class NaturalCmp
        include Comparable
        attr_accessor :chunks
    
        def initialize(s)
            @chunks = s.scan(/\D+|\d+/).map { |x| x =~ /\d/ ? x.to_i : x }
        end
    
        def <=>(other)
            i = 0
            @chunks.inject(0) do |cmp, e|
                oe = other.chunks[i]
                i += 1
                if(cmp == 0)
                    cmp = e.class == oe.class \
                        ? e      <=> oe \
                        : e.to_s <=> oe.to_s
                end
                cmp
            end
        end
    end
    
    my_array.sort_by { |e| NaturalCmp.new(e['id']) }
    

    The basic idea here is to push the comparison noise off to another class to keep the sort_by from degenerating into an incomprehensible mess. Then we use the same scanning as before to break the strings into pieces and implement the array <=> comparator by hand. If we have two things of the same class then we let that class’s <=> deal with it otherwise we force both components to String and compare them as such. And we only care about the first non-0 result.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there some difference in the following deletions of object array? The first way:
I'm trying to find the best way to put circumflex accents ( ˆ =
There's a lot one can find about this googling a bit but I haven't
I'm sure there is a correct way to do this, I'm new to objective-c
How do you pass options to an executable? Is there an easier way than
Is there any feasible way of using generics to create a Math library that
I'm not sure the best way to design this, so here goes: I'm tracking
I've just cloned the Android kernel (via git clone ) repository but for some
There is a conversion process that is needed when migrating Visual Studio 2005 web
There are two weird operators in C#: the true operator the false operator If

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.