From: Robert Klemme Date: 2012-06-28T18:06:17+09:00 Subject: Re: Is this the correct use of rand? On Thu, Jun 28, 2012 at 9:44 AM, Emeka Patrick wrote: > In the example below why was it necessary to put (max+1)? Couldn't that > result in the generation of a random number up to and including 50? > > This code calls a code blocklimittimes, each time passing in a random > number betweenminandmax: > >  def pick_random_numbers(min, max, limit) >    limit.times { yield min+rand(max+1) } >  end I am surprised nobody mentioned that code is flawed because it does not adherer to the mentioned contract: the code will yield random numbers outside the range given by min and max. Demonstration: irb(main):005:0> pick_random_numbers(10, 11, 20){|r| p r} 15 20 17 10 10 12 17 15 21 12 11 21 12 13 11 17 19 17 10 18 => 20 You need def pick_random_numbers(min, max, limit) limit.times { yield min + rand(max + 1 - min) } end Or use the range version as has been mentioned. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/