44

I've the following but it doesn't work:

<%= (5..30).sample %>
user1049097
  • 1,901
  • 4
  • 22
  • 35

4 Answers4

111

Give this a shot.

<%= [*5..30].sample %>

...or...

<%= rand(5..30) %>
alex
  • 479,566
  • 201
  • 878
  • 984
  • 6
    The first solution is inefficient. Good thing it's not a random number between 5 and a million... The second solution works only in Ruby 1.9.3. This question has been answered before: http://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby – Marc-André Lafortune Nov 18 '11 at 06:44
  • @Marc-AndréLaortune: Yeah, I agree, on all things. I'll throw in my close vote. – alex Nov 18 '11 at 06:56
  • 3
    Rand is much more efficient – Erowlin Aug 03 '13 at 11:38
6

This would generate a random number in that range:

5 + rand(25)

Simply add the min to the rand(max-min).

mduvall
  • 1,018
  • 1
  • 8
  • 15
6

Range has no #sample method. Use the one from Array instead.

<%= (5..30).to_a.sample %>
Guilherme Bernal
  • 8,183
  • 25
  • 43
3

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)
stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189