From: Paul Duncan Date: 2002-04-03T13:26:29+09:00 Subject: Re: rcr --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: >=20 > [3, 2, 5, 2, 19].rand_item # =3D> returns random item from array >=20 > 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=20 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 =3D %w(asdf hey matz ruby rocks test 123) 4.times { puts arr.rand } [].rand -- produces (for this particular run): hey matz rocks hey =2E/array_random.rb:5:in `rand': Array#rand(): empty array (RuntimeError) from ./array_random.rb:15 > regards > repeater --=20 Paul Duncan 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= =ENdn -----END PGP SIGNATURE----- --DSayHWYpDlRfCAAQ--