Created
August 14, 2009 18:46
-
-
Save danielpcox/168012 to your computer and use it in GitHub Desktop.
Array#sample : I recently moved a project from ruby 1.9.1 to ruby 1.8.6, which doesn't have Array#sample. I couldn't find it online quickly, so I wrote one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Array#sample | |
# I recently moved a project from ruby 1.9.1 to ruby 1.8.6, which doesn't have | |
# Array#sample. I couldn't find it online quickly, so I wrote one. | |
class Array | |
def sample(sample_size=1, acc=[]) | |
sample_size = self.size if acc.empty? && sample_size > self.size | |
return acc if sample_size==0 | |
index_to_sample = (rand * self.size).floor | |
if acc.include?(self[index_to_sample]) | |
sample(sample_size, acc) | |
else | |
sample( sample_size-1, acc<<self[index_to_sample] ) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment