Sunday, 27 November 2011

Snippet: random range

Being able to get a random number within a given range is something currently only available in ruby 1.9... but if you want to add a quick method that will do it for you, this one does the trick:

  def rand_in_range(val1,val2)
    rand(1+val2-val1)+val1
  end

  rand_in_range(1,5) # => one of: 1,2,3,4,5

  rand_in_range(100,999) # => anywhere from 100 to 999

Note: it only works for integer values...

2 comments:

fredb said...

range_rand(1,5)
range_rand(100,999)

Right?

Taryn said...

Yes! thanks... fixed now.