--DSayHWYpDlRfCAAQ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable * repeater (repeater / lucentprimate.cjb.net) wrote: > i've not used ruby for that long, but i've found the need to do the > following rather often: > > [3, 2, 5, 2, 19].rand_item # => returns random item from array > > short code, but could be helpful to others (needed it in all of my last > projects, but perhaps i'm just strange) Were you asking for code to return a random element, or saying you have code that returns a random element? If it's the latter, here's a quick answer: -- class Array def rand raise RuntimeError, 'Array#rand(): empty array' unless length > 0 at Kernel::rand(length).floor end end # test Array#rand() arr = %w(asdf hey matz ruby rocks test 123) 4.times { puts arr.rand } [].rand -- produces (for this particular run): hey matz rocks hey ./array_random.rb:5:in `rand': Array#rand(): empty array (RuntimeError) from ./array_random.rb:15 > regards > repeater -- Paul Duncan <pabs / pablotron.org> pabs on #gah (OPN IRC) http://www.pablotron.org/ OpenPGP Key ID: 0x82C29562 --DSayHWYpDlRfCAAQ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8qoRyzdlT34LClWIRAhhRAJ9Z4SOwpdFLf+pyZB6Tlba+e5pcDgCfd+HU C6td1wo5lMfRYxDjNj+WIi0ßÅn -----END PGP SIGNATURE----- --DSayHWYpDlRfCAAQ--