Last Updated: February 25, 2016
·
1.067K
· manudwarf

One-line ruby weighted shuffle

I came across a specific need in AOL, and thought my solution would be helpful to other people.

Basically, we have a list of (let's say) cats. I want 10 random cats from this list, but some should appear more that others, according to a weight attribute (>0).

Well, pretty simple actually :

cats.sort_by { |cat| - cat.weight * rand() }

The - is necessary because sort_by works from the lowest value to the highest, which is the opposite of what we intend to do.

Enjoy :)