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)
Notice that the last statement in your method is the
while
loop, which will not execute ifproducts
is empty. Hence function returnsnil
.Try like this:
Note however, that this has a potential of getting into an infinite loop once all numbers from 100 to 999 are in
products
then every time you need a new id
This guarantees that numbers are never reused. Of course, you'll have problems when you run out of elements on the array.
Your function returns the while expression which is always nil. You should return the number instead:
Note that you can remove duplication by placing "while" after key generation:
And you can omit
begin end
for a single expression