Generate a Random Number with 7 Digits

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.

6 Answers

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
5

It's an instance method:

puts Random.new.rand(1_000_000..10_000_000-1) 
1

I find this more readable:

7.times.map { rand(1..9) }.join.to_i
0

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).

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
1

Another option with ruby 1.8.7 compatibility:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest