From: Brian Candler Date: 2009-12-30T07:01:00+09:00 Subject: Re: Question abour rand() Panagiotis Atmatzidis wrote: > I'm looking for a way to create a random sequence of numbers using the > 'rand' method. Others have answered the 'random number between 1950 and 2000' bit. In terms of creating a "sequence" of these values, here are a couple of options to consider. (1) Build an array. a = [] 10.times { a << rand(50) } This array (a) is an object which can be returned, passed to other functions etc. The above code hard-codes the number of values to build (10), but you could choose this dynamically at run-time instead. (2) Yield the values. For code which wants to "return" multiple values, you can instead "yield" the values to a block which the caller provides. You can yield multiple times, thus calling the block multiple times. In other programming languages you might call this a "callback function" def generate_random(n=10) n.times do yield rand(50) end end generate_random do |r| puts "I got #{r}!" end Note that you can legitimately yield an infinite number of times, because the block can abort the sequence when it wants. So in the following example, the user of the function decides when they don't want any more random numbers: def generate_infinite loop do yield rand(50) end end count = 0 generate_infinite do |r| puts "I got #{r}!" count += 1 break unless count < 10 end A more advanced way to do this is with an 'Enumerator' object, but I'd say you should start with the above for now. -- Posted via http://www.ruby-forum.com/.