2

This question goes over how to select random elements from an array using sample, but I'd like to do this multiple times, selecting a unique one each time.

The simplest solution I can think of is something like this, but I feel like there must be a simpler way (without modifying the original array):

myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]

selected = []

first = myArray.sample
selected << first

second = myArray.sample
while(selected.include? second) do
  second = myArray.sample
end

selected << second

EDIT:

In my specific case, I am not immediately calling one after the other, so using an argument with sample won't help

Community
  • 1
  • 1
Tom Prats
  • 7,364
  • 9
  • 47
  • 77

3 Answers3

3

You can do:

(myArray - selected).sample

E.g. if:

selected = ['ruby', 'goodies']

then:

myArray - selected #=> ["stuff", "widget", "java", "emerald", "etc"]

So, the sample will be taken out of ["stuff", "widget", "java", "emerald", "etc"].

Mischa
  • 42,876
  • 8
  • 99
  • 111
2

You can pass additional argument number to sample(n) and it will return a new array for you

myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
n = myArray.length

# The elements are chosen by using random and unique indices and doesn’t repeat itself 
selected = myArray.sample(n)

Second option is to use slice! and rand with seed:

myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
myArray_copy = myArray
selected = []

selected << myArray_copy.slice!(rand(myArray_copy.length - 1))
hawk
  • 5,409
  • 2
  • 23
  • 29
  • i dont call it all at once though, so this won't help me (but is a valid answer for the stated question) – Tom Prats Sep 06 '13 at 04:10
0

You can just use the method uniq. Assuming your array is ary, call:

 ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61