How to get a random number in Ruby

2019-01-01 16:22发布

How do I generate a random number between 0 and n?

18条回答
春风洒进眼中
2楼-- · 2019-01-01 16:55

While you can use rand(42-10) + 10 to get a random number between 10 and 42 (where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:

rand(10...42) # => 13

Available for all versions of Ruby by requiring my backports gem.

Ruby 1.9.2 also introduced the Random class so you can create your own random number generator objects and has a nice API:

r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"

The Random class itself acts as a random generator, so you call directly:

Random.rand(10...42) # => same as rand(10...42)

Notes on Random.new

In most cases, the simplest is to use rand or Random.rand. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.

If you use Random.new, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.new and use it everywhere else.

The cases where Random.new is helpful are the following:

  • you are writing a gem and don't want to interfere with the sequence of rand/Random.rand that the main programs might be relying on
  • you want separate reproducible sequences of random numbers (say one per thread)
  • you want to be able to save and resume a reproducible sequence of random numbers (easy as Random objects can marshalled)
查看更多
临风纵饮
3楼-- · 2019-01-01 16:55

you can do rand(range)

x = rand(1..5)
查看更多
谁念西风独自凉
4楼-- · 2019-01-01 16:55

Don't forget to seed the RNG with srand() first.

查看更多
人间绝色
5楼-- · 2019-01-01 16:58
rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.

查看更多
低头抚发
6楼-- · 2019-01-01 16:59

This link is going to be helpful regarding this;

http://ruby-doc.org/core-1.9.3/Random.html

And some more clarity below over the random numbers in ruby;

Generate an integer from 0 to 10

puts (rand() * 10).to_i

Generate a number from 0 to 10 In a more readable way

puts rand(10)

Generate a number from 10 to 15 Including 15

puts rand(10..15)

Non-Random Random Numbers

Generate the same sequence of numbers every time the program is run

srand(5)

Generate 10 random numbers

puts (0..10).map{rand(0..10)}
查看更多
美炸的是我
7楼-- · 2019-01-01 17:03

Try array#shuffle method for randomization

array = (1..10).to_a
array.shuffle.first
查看更多
登录 后发表回答