如何在Ruby中生成a和b之间的随机数?
例如,要生成 3 到 10 之间的随机数,我使用: rand(8) + 3
有没有更好的方法来执行此操作(例如 rand(3, 10)< /代码>) ?
To generate a random number between 3 and 10, for example, I use: rand(8) + 3
Is there a nicer way to do this (something like rand(3, 10)
) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
更新:Ruby 1.9.3
Kernel#rand
也接受范围http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
转换为数组可能成本太高,而且没有必要。
或者
Array#sample
Ruby 1.8 中的标准.7+。
注意:在1.8.7中被命名为#choice,在以后的版本中被重命名。
但是无论如何,生成数组需要资源,你已经写的解决方案是最好的,你可以这样做。
UPDATE: Ruby 1.9.3
Kernel#rand
also accepts rangeshttp://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
Converting to array may be too expensive, and it's unnecessary.
Or
Array#sample
Standard in Ruby 1.8.7+.
Note: was named #choice in 1.8.7 and renamed in later versions.
But anyway, generating array need resources, and solution you already wrote is the best, you can do.
其中
a
是最低值,b
是最高值。Where
a
is your lowest value andb
is your highest value.内核#rand
Kernel#rand
您可以使用范围运算符。请注意两种形式之间的区别:
You can use range operators. Do note the difference between the two forms:
请参阅这个答案:Ruby 1.9.2中有,但在早期版本中则不然。我个人认为 rand(8) + 3 很好,但如果您有兴趣,请查看链接中描述的 Random 类。
See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.
10 和 10**24
For 10 and 10**24
这是
#sample
和#rand
的快速基准测试:因此,执行
rand(a..b)
是正确的做法And here is a quick benchmark for both
#sample
and#rand
:So, doing
rand(a..b)
is the right thing