Last active
August 29, 2015 13:55
-
-
Save robmiller/8783371 to your computer and use it in GitHub Desktop.
Select a random n values from an array that might have < n values
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
words = %w{foo bar baz} | |
n = 10 | |
# If we use sample, we get a random order but never | |
# more than 3 entries: | |
words.sample(n) | |
# => ["bar", "foo", "baz"] | |
# A solution: | |
n.times.map { words.sample } | |
# => ["baz", "bar", "bar", "foo", "foo", "bar", "bar", "foo", "bar", "foo"] | |
# Another: | |
words.cycle.take(n).shuffle | |
# => ["bar", "baz", "foo", "bar", "baz", "bar", "baz", "foo", "foo", "foo"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment