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 :)
Written by Emmanuel Bourgerie
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#