HOW-TO produce random numbers within a range?

R

Ruby N00bie

Hello,
Thanks for reading this.
I am very new to Ruby and have been learning using a tutorial at
http://pine.fm/LearnToProgram/
by Chris (thanks Chris)
After searching fairly thoroughly in forums and tutorials I found no
answer to my problem.
I have come to a point where i need to generate a random number within a
range.

I have learnt that rand(100) produces random numbers from 0 to 99 but i
need to know how to set a minimum for the random number.

Your help would be greatly appreciated.

Thanks in advance, tckl.
 
R

Rimantas Liubertas

I have learnt that rand(100) produces random numbers from 0 to 99 but i
need to know how to set a minimum for the random number.

Your help would be greatly appreciated.
<...>

Add the minimum :)

def range_rand(min,max)
min + rand(max-min)
end
 
R

Rodrigo Bermejo

Welcome abord !


Easier to make it fit it that fit your self.
The Ultimate Morphing Lego Game.


#!/usr/bin/my_new_lego_game

alias old_rand rand

def rand(min,max)
until min < r=old_rand(max); end
return r
end


10.times do |x|
p rand(1,10)
end


-.rb
 
W

William James

Ruby said:
Hello,
Thanks for reading this.
I am very new to Ruby and have been learning using a tutorial at
http://pine.fm/LearnToProgram/
by Chris (thanks Chris)
After searching fairly thoroughly in forums and tutorials I found no
answer to my problem.
I have come to a point where i need to generate a random number within a
range.

I have learnt that rand(100) produces random numbers from 0 to 99 but i
need to know how to set a minimum for the random number.

Your help would be greatly appreciated.

Thanks in advance, tckl.

You don't need to be able to set a minimum. You simply take what
rand() gives you and add an offset.
57 51 51 58 54 53 56 58 54 57 54 56 57 58 50 56 56 50 58 52 58 55 53 50
56 => 25
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top