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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With