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 540795
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T10:16:38+00:00 2026-05-13T10:16:38+00:00

I think this is a great Ruby one-liner: someArray.sort_by {rand} It’s concise, it’s readable,

  • 0

I think this is a great Ruby one-liner:

someArray.sort_by {rand}

It’s concise, it’s readable, and it works – but I don’t quite understand how. Here’s what I know:

  1. rand evaluates to a number between 0 and 1 (like 0.783468632804653)
  2. rand is being repeatedly evaluated in the code above, because assigning it to x first breaks the random sort
  3. sort_by {0.783468632804653}, or any other number I tried, has no effect on the array

ruby-doc.org wasn’t much help to me in this case.

Can someone explain this step-by-step?

Update

I’ve been using Ruby longer now, and I see that I was missing a concept or two here. The key thing is that:

  1. rand is a method (defined on Kernel); it generates a random number
  2. {rand} is a block, which sort_by keeps, calling it each time it wants to compare two items in the collection. If the collection is a bunch of objects representing countries, it needs to be able to grab two of them and determine which one comes first. Do you put the one with the longest name first? The one with the largest land mass? The block should answer that question by returning a value that says "you asked about Spain vs Cameroon, and I say Cameroon comes first." (You could do that with {|country| country.name.length}

The rest of how sort_by works is explained in the documentation. I’m still not quite sure why returning a random number works at all – presumably sort_by rounds it to -1, 0, or 1, whichever is closest? But in any case, getting a different random number every time you call the block is quite different from getting the same number every time. When sort_by says "which of these two countries comes first?", {rand} puts on a blindfold, turns around 10 times, points and says "that one!" 🙂

  • 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-13T10:16:38+00:00Added an answer on May 13, 2026 at 10:16 am

    In Ruby 1.8/1.9 both sort and sort_by are implemented in C, this is a rough equivalent of how this works:

    Say you start with [1,2,3,4] and call sort_by{rand}:

    1. (I invented some random numbers):

      An array of tuples is created: [[0.12232, 1],[0.53434, 2],[0.333, 3],[0.99, 4]]

      In roughly equivalent Ruby code this is: [1,2,3,4].map{|x| [rand, x]}

    2. Ruby’s quick sort is performed on the array based off the first element: (note the internal implementation is far from trivial and contains a ton of optimisations for already ordered arrays and such)

      [[0.12232, 1],[0.333, 3],[0.53434, 2],[0.99, 4]]
      

      In rough Ruby this step is: ary.sort{|x,y| x[0] <=> y[0]}

    3. Pointers are copied from the new sorted array, to the correct position in the original array.

      [1,3,2,4]
      

      In rough Ruby this step is: ary.map{|x,y| y}

    This technique is sometimes referred to as a “Schwartzian Transform“. Caching means that the expensive operation is not performed more than N times. Meaning, this is a very efficient way of randomizing an array.

    Note: array.shuffle! will be the most efficient built-in way to shuffle an array (in-place) since it uses a modern version of Fisher-Yates:

    static VALUE
    rb_ary_shuffle_bang(VALUE ary)
    {
        long i = RARRAY_LEN(ary);
    
        rb_ary_modify(ary);
        while (i) {
      long j = rb_genrand_real()*i;
      VALUE tmp = RARRAY_PTR(ary)[--i];
      RARRAY_PTR(ary)[i] = RARRAY_PTR(ary)[j];
      RARRAY_PTR(ary)[j] = tmp;
        }
        return ary;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this small snipped of code. I don't know ruby and I think
So, I started with this: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Ruby Which works great for really small strings. But,
in C# 3, initializers were added. This is a great feature. However, one thing
I think this could be a very easy question for you. But I have
(I think this is a pretty basic question on OOP, but unfortunately I wasn't
I think this is a pretty straightforward problem but... var outerHeight = $('.profile').outerHeight(); $(#total-height).text(outerHeight
I think this is mostly because I'm new to PHP OOP, but I have
I think this question has been asked many a times but I've been searching
As a Ruby/Rails dabbler, one of the things that's long bothered me is this
One thing I love about ruby is that mostly it is a very readable

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.