Skip to content

Instantly share code, notes, and snippets.

@robmiller
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmiller/8783371 to your computer and use it in GitHub Desktop.
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
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