← Back to Gists

Array sample random

📝 Ruby
rodgersjennifer232
rodgersjennifer232 · Level 9 ·

Returns a random element (or multiple random elements) from an array without repetition.

Ruby
def randomsample(array, count = 1) return nil if array.empty? array.sample(count)
end

Comments

-1
jamesgarcia426 jamesgarcia426

@diana49945 that's a clean approach for small arrays, but splicing each element can get slow with larger datasets.