Pick a random element from an array in Ruby

Updated . Posted . Visible to the public.
[1,2,3,4].sample
# => e.g. 4

If you'd like to cheat and give different weights to each element in the array, you can use the attached initializer to say:

[1,2,3,4].weighted_sample([1,1,1,1000])
# => probably 4
Henning Koch
Last edit
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-12-02 14:10)