Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random number with a seed between a range in ruby

Tags:

random

ruby

I'm trying to get the banner image on my website to change once a day. I can see ruby has srand which will let me input a number for the date and return the same result every time it is called on the same day but this returns a very long number. I also saw rand lets me use a range like rand(a..b).

Is there any way I can use srand with a range like I can with rand?

like image 331
Qwertie Avatar asked Oct 28 '25 09:10

Qwertie


1 Answers

You can create a special/designated random number generator with any seed value you like:

special = Random.new 42 # create a new instance of Random seeded with 42
20.times { p special.rand(5..10) } # generate 20 random ints in range 5 to 10

Your special instance of Random is independent of kernel#rand unless you use srand to initialize it with the same seed value.

like image 137
pjs Avatar answered Oct 30 '25 10:10

pjs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!