Ruby-on-rails 如何打印出范围之间的随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8176238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print out a random number between a range?
提问by user1049097
I've the following but it doesn't work:
我有以下但它不起作用:
<%= (5..30).sample %>
回答by alex
Give this a shot.
试一试。
<%= [*5..30].sample %>
...or...
...或者...
<%= rand(5..30) %>
回答by mduvall
This would generate a random number in that range:
这将生成该范围内的随机数:
5 + rand(25)
Simply add the min to the rand(max-min).
只需将最小值添加到 rand(max-min)。
回答by Guilherme Bernal
Rangehas no #samplemethod. Use the one from Arrayinstead.
Range没有#sample方法。改用那个 from Array。
<%= (5..30).to_a.sample %>
回答by stephenmurdoch
for 1 random number:
对于 1 个随机数:
a = (5...30).sort_by{rand}[1]
# => 7
It seems more verbose than what others have suggested, but from here, it's easy to pick three random unique numbers from the same range:
这似乎比其他人建议的更冗长,但从这里,很容易从同一范围内选择三个随机的唯一数字:
a = (5...30).sort_by{rand}[1..3]
# => [19, 22, 28]
Or 20:
或 20:
a = (5...30).sort_by{rand}[1..20]
# => [7, 12, 16, 14, 13, 15, 22, 17, 24, 19, 20, 10, 21, 26, 29, 9, 23, 27, 8, 18]
Might come in useful for someone who needs to display 5 random foos in their sidebar
可能对需要在侧边栏中显示 5 个随机 foos 的人有用
EDIT:Thanks to Marc-Andre Lafortune, I discovered that the following is much better:
编辑:感谢 Marc-Andre Lafortune,我发现以下内容要好得多:
a=[*5..30].sample(3)

