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.

6 Answers 6

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 
Sign up to request clarification or add additional context in comments.

5 Comments

I'm using ruby 1.8.7, Random doesnt' seem to exist. is it a gem?
@Blankman: Did you try require 'random', and also checking if it's 1.9.2 only?
1.8.7 doesn't have Random. It's in 1.9.2+. Install the backports gem and you'll inherit it in 1.8.7, along with lots of other juicy goodness.
what are the ramifications of installing backport? (if any)
Just use rand, not Random.rand. It works all the way back as far as 1.6.0
6

It's an instance method:

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

1 Comment

1_000_000...10_000_000 is more Ruby-ish.
3

I find this more readable:

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

Comments

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

Comments

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 

1 Comment

Needed a way to avoid zeros
0

Another option with ruby 1.8.7 compatibility:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.