Juliano Juliano - 1 year ago 77
Ruby Question

Why does random work like this in Ruby?

I was trying to be clever about deterministically picking random stuff, and found this:

irb(main):011:0> Random.new(Random.new(1).rand + 1).rand == Random.new(1).rand
=> true
irb(main):012:0> Random.new(Random.new(5).rand + 1).rand == Random.new(5).rand
=> false
irb(main):013:0> Random.new(Random.new(5).rand + 5).rand == Random.new(5).rand
=> true

For a second, I thought "wow, maybe that's a property of random number generators", but Python and C# fail to reproduce this.

Answer Source

You’re probably going to be disappointed with this one. Let’s take a look at the output of rand:

irb(main):001:0> Random.rand

It’s a number in the range [0, 1). Random.new accepts an integer seed.

irb(main):002:0> Random.new(5.5) == Random.new(5)

Mystery solved!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download