I assume the documentation is wrong. If you use "srand" instead of
"srand(0)" the behavior is as documented for the case that 0 is used,
i.e. the numbers really change. With 0 I get a fixed sequence.
$ for i in `seq 1 5`; do ruby -e 'srand 0;p 10.times.map {rand(10)}'; done
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
RKlemme@padrklemme2
/cygdrive/c/SCMws/RKlemme/JavaProducts_oslee_ngcp_dev_R3.1_vf_fiji_be4rb
$ for i in `seq 1 5`; do ruby -e 'srand;p 10.times.map {rand(10)}'; done
[5, 8, 6, 0, 1, 6, 9, 1, 3, 3]
[0, 8, 4, 1, 7, 1, 8, 8, 9, 5]
[4, 3, 3, 7, 1, 5, 2, 4, 4, 1]
[1, 1, 4, 5, 3, 2, 6, 2, 7, 0]
[1, 6, 8, 5, 0, 8, 4, 0, 4, 3]
Without calling srand we get random sequences as well:
RKlemme@padrklemme2
/cygdrive/c/SCMws/RKlemme/JavaProducts_oslee_ngcp_dev_R3.1_vf_fiji_be4rb
$ for i in `seq 1 5`; do ruby -e 'p 10.times.map {rand(10)}'; done
[7, 6, 6, 5, 1, 7, 8, 9, 2, 1]
[1, 8, 7, 5, 2, 3, 1, 6, 3, 8]
[0, 4, 8, 0, 9, 2, 5, 2, 1, 4]
[5, 7, 0, 9, 3, 8, 1, 4, 9, 4]
[2, 6, 5, 8, 1, 8, 4, 5, 4, 2]
Basically the "or zero" must be removed from the doc.
Kind regards
robert
···
On Mon, Aug 29, 2011 at 1:20 PM, Samuel Mensah <sasogeek@yahoo.com> wrote:
I'm fairly new to coding ruby and I'm using "Learn to program" by Chris
Pine.
After taking a look at the 'rand' method, I'm introduced to 'srand' and
here's what I'm confused about...
srand(123)
puts rand(100)
puts rand(100)
...will give me 2 random numbers which will repeat themselves for as
many times as the program is run but according to the book "If you want
to get different numbers again (like what happens if you
never use srand), then just call srand(0)." I don't understand what it
means cos this is what I tried...
srand(0)
puts rand(100)
puts rand(100)
...and only the first 2 numbers changed after it was run again and they
kept repeating every time it is run. what exactly does the book mean and
how is it written in code?
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/