In Ruby, how do you generate a random number between 0 and n? In .NET you can create a Random object, does something like this exist for Ruby?
Well, I figured it out. Apparently there is a builtin (?) function called rand:
rand(n + 1)
If someone answers with a more detailed answer, I'll mark that as the correct answer.
What is wrong with rand(range) ?
If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).
Finally, if you just need a random float, just call rand with no arguments.
(From first result of google search: Ruby Random Numbers)
As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).
For instance, in this game where you need to guess 10 numbers, you can initialize them with:
10.times.map{ Random.new.rand(20..30) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
Apparently srand is called when the ruby interpreter is started.
Therefore unless you have a specific need to reset the seed - extra calls to srand are unnecessary.
Ruby 1.9.2 introduces the Random
class, so while you can still use rand
, you can now create your own random number generator object. It can be marshaled, among other things.
r = Random.new(42)
r.rand(0...100) # => 51
Available for all versions of Ruby by requiring my backports
gem.