From: Daniel Martin Date: 2006-07-28T03:45:46+09:00 Subject: Re: rand(-10..10) Daniel Schierbeck writes: >>> This should work with all enumerables: >>> >>> module Enumerable >>> def rand >>> entries = entries >>> entries.at(Kernel.rand(entries.length)) >>> end >>> end >>> >>> I can't seem to get around the `entries = entries' part -- I don't want >>> to convert the enumerable to an array more than once. Any ideas? There's also this, which is possibly more memory-efficient (if the Enumerable in question chews large amounts of memory when being converted to an array, but not with each), but is almost certainly much slower, since it calls rand once per element: module Enumerable def rand ret, i = nil, 0 each {|v| ret = v if 0 == Kernel.rand(i += 1)} ret end end Test code for irb: h=Hash.new(0); 10000.times {h[%w{a b c d e}.rand] += 1}; h