Skip to content

Instantly share code, notes, and snippets.

@danielpcox
Created August 14, 2009 18:46
Show Gist options
  • Save danielpcox/168012 to your computer and use it in GitHub Desktop.
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.
# 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