Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License
module Mongoid
  class Criteria
    def sample(n = 1)
      indexes = (0..self.count-1).sort_by{ rand }.slice(0,n).collect!
      if n == 1
        return self.skip(indexes.first).first
      else
        return indexes.map{ |index| self.skip(index).first }
      end
    end
  end
end

https://gist.github.com/3113975

Can we do better?