例如,要生成3到10之间的随机数,我使用:rand(8) + 3
有没有更好的方法(比如rand(3,10)) ?
例如,要生成3到10之间的随机数,我使用:rand(8) + 3
有没有更好的方法(比如rand(3,10)) ?
当前回答
10和10**24
rand(10**24-10)+10
其他回答
下面是#sample和#rand的快速基准测试:
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1* x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1> x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
user system total real
sample 3.870000 0.020000 3.890000 ( 3.888147)
rand 0.150000 0.000000 0.150000 ( 0.153557)
所以选rand(a。b)是正确的
请看这个答案:在Ruby 1.9.2中有,但在早期版本中没有。我个人认为rand(8) + 3很好,但如果你感兴趣,可以查看链接中描述的Random类。
更新:Ruby 1.9.3 Kernel#rand也接受范围
rand(a..b)
http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
转换为数组的代价可能太大,而且没有必要。
(a..b).to_a.sample
Or
[*a..b].sample
数组#样品
标准的Ruby 1.8.7+。 注意:在1.8.7中被命名为#choice,在后续版本中被重命名。
但无论如何,生成数组需要资源,你已经写的解决方案是最好的,你可以做到。
def random_int(min, max)
rand(max - min) + min
end
Random.new.rand(a..b)
a是最小值,b是最大值。