为了生成一个介于3和10之间的随机数,例如,我使用以下代码:
rand(8) + 3
有没有更好的方法来实现这个(类似于rand(3, 10)
)?更新: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
或者
[*a..b].sample
在Ruby 1.8.7+中是标准的。
注意:在1.8.7中被命名为#choice,后来改名了。
但无论如何,生成数组需要资源,你已经编写的解决方案是最好的,你可以这样做。
ruby 2.0.0-p247
上可以工作,所以我撤回之前的说法。 - fguillen1000000.times{|i| a = rand(1000..9999); puts a if a < 1000}
没有输出任何一个数字。 - PelleRandom.new.rand(a..b)
其中 a
为您的最小值,b
为您的最大值。
rand()
,那么你调用的是 Kernel#rand
,它仅支持一个 max
参数。如果你想传递一个范围,你必须使用 Random#rand
,也就是说你必须按照这种方式实现。+1 - grumpit3..10 # includes 10
3...10 # doesn't include 10
def random_int(min, max)
rand(max - min) + min
end
对于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)
是正确的做法。
def my_rand(x, y) rand(y - x) + x end
这段代码的作用是生成在x
和y
之间的一个随机整数,包括x
和y
。 - Theoy - x + 1
。 - Nakilonrand(3..10)
- eikes