Read more

Pick a random element from an array in Ruby

Henning Koch
December 02, 2011Software engineer at makandra GmbH
[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
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot
Posted by Henning Koch to makandra dev (2011-12-02 15:10)