9

How can I produce a random number in a range from 1 million to 10 million?

rand(10) works, I tried rand(1..10) and that didn't work.

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

6 Answers6

13

Take your base number, 1,000,000 and add a random number from 0 up to your max - starting number:

 1_000_000 + Random.rand(10_000_000 - 1_000_000) #=> 3084592
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
6

It's an instance method:

puts Random.new.rand(1_000_000..10_000_000-1) 
steenslag
  • 79,051
  • 16
  • 138
  • 171
3

I find this more readable:

7.times.map { rand(1..9) }.join.to_i
Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
1

Or, in case performance is not an issue and you don't want to count zeros:

(0...7).map { |i| rand((i == 0 ? 1 : 0)..9) }.join.to_i
Sebastian
  • 2,109
  • 1
  • 20
  • 15
1

This will generate a random number between 1,000,000 and 9,999,999.

rand(10_000_000-1_000_000)+1_000_000

This works in 1.8.7 without any gems(backports, etc).

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
0

Another option with ruby 1.8.7 compatibility:

rand(9999999999).to_s.center(10, rand(9).to_s).to_i

Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115