Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking random element from an array in Ruby ONCE ONLY

I know I can pick a random element out of an array with the sample method but this leaves the possibility of an element being picked more than once. I could shuffle the array first and then go from first to last element in order but I understand this is memory intensive and I am looking for a less intensive method if possible!

like image 532
Spike Fitsch Avatar asked May 12 '26 02:05

Spike Fitsch


1 Answers

sample takes an argument:

[*(1..10)].sample(5) #=>[3, 4, 1, 8, 9] 

No element will be selected twice.

like image 142
steenslag Avatar answered May 14 '26 18:05

steenslag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!