I've the following but it doesn't work:
<%= (5..30).sample %>
Give this a shot.
<%= [*5..30].sample %>
...or...
<%= rand(5..30) %>
This would generate a random number in that range:
5 + rand(25)
Simply add the min to the rand(max-min).
Range
has no #sample
method. Use the one from Array
instead.
<%= (5..30).to_a.sample %>
for 1 random number:
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:
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
EDIT: Thanks to Marc-Andre Lafortune, I discovered that the following is much better:
a=[*5..30].sample(3)