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 17:07

You can simply use random_number.

If a positive integer is given as n, random_number returns an integer: 0 <= random_number < n.

Use it like this:

any_number = SecureRandom.random_number(100) 

The output will be any number between 0 and 100.

查看更多
美炸的是我
3楼-- · 2019-01-01 17:08

Use rand(range)

From Ruby Random Numbers:

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.


As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.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{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

查看更多
妖精总统
4楼-- · 2019-01-01 17:08

Easy way to get random number in ruby is,

def random    
  (1..10).to_a.sample.to_s
end
查看更多
琉璃瓶的回忆
5楼-- · 2019-01-01 17:12

If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandom module found its way from ActiveSupport to the ruby core in 1.9.2+. So without the need for a full blown framework:

require 'securerandom'

p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88

p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409

p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"

It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)

查看更多
回忆,回不去的记忆
6楼-- · 2019-01-01 17:12

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.

查看更多
冷夜・残月
7楼-- · 2019-01-01 17:12

Simplest answer to the question:

rand(0..n)
查看更多
登录 后发表回答