Yes - the code is wrong. A correct implementation would adjust the probability of sampling based on how many items have been trialed.
EDIT: I misread it as rand(n), rand(idx) is correct.
EDIT: I misread it as rand(n), rand(idx) is correct.
Though, I think there is an off-by one in this implementation (assuming that Ruby indexing starts at 0):
j = rand(idx)
out[j] = i if j < n
Say that the index is n, it will call rand(n), which gives a random number [0..n). However, the index should be picked from [0..n].That sounded right to me. I could be convinced otherwise.
Suppose that the sample size is 1 and you are getting the second item (index 1). You will call rand(1), which has 0 as the only possible outcome. So, you will always replace the first item (index 0). Whereas if you would call rand(2) (possible outcomes: 0 and 1), you replace the item in the sample with probability .5 (assuming that the random number generator is uniform).
I'll fix the code and publish a new gem a bit later today. Thanks!
j = rand(idx)
out[j] = i if j < n
..it is keeping the sampling probability at n/idx where n is the sample/reservoir size and idx is the number of items seen so far. Then if this item is selected for sampling, each of the n items in the reservoir is equally likely to be replaced. I think the implementation is correct, assuming that idx is the number of items seen so far.