Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate non-repeating random numbers in Ruby

Tags:

random

ruby

I want to generates a sequence of unique random number between 100 and 999. I want to make sure that no numbers are generated twice, to ensure that each number is unique. Here is what I came up with. It does not work. When i run it, the screen is just blank. Can anyone help me?

products = {}

def random_key(products)

  rand_key = rand(900) + 100

  while products.has_key?(rand_key)

    rand_key = rand(900) + 100

  end

end

puts random_key(products)
like image 298
eddie tuell Avatar asked May 11 '26 19:05

eddie tuell


1 Answers

a = (100..999).to_a.shuffle 

then every time you need a new id

new_id = a.pop

This guarantees that numbers are never reused. Of course, you'll have problems when you run out of elements on the array.

like image 92
Marc Talbot Avatar answered May 14 '26 14:05

Marc Talbot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!