Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random number with 7 digits

Tags:

ruby

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.

like image 541
Blankman Avatar asked Apr 19 '11 21:04

Blankman


3 Answers

I find this more readable:

7.times.map { rand(1..9) }.join.to_i
like image 128
Arturo Herrero Avatar answered Oct 26 '22 18:10

Arturo Herrero


It's an instance method:

puts Random.new.rand(1_000_000..10_000_000-1) 
like image 42
steenslag Avatar answered Oct 26 '22 17:10

steenslag


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
like image 31
the Tin Man Avatar answered Oct 26 '22 18:10

the Tin Man