# Randomize array content

**URL:** <https://www.ruby-forum.com/t/randomize-array-content/105320>\
**Category:** Ruby\
**Created:** [May 28, 2007, 8:00pm UTC](https://www.ruby-forum.com/t/randomize-array-content/105320 "2007-05-28T20:00:58Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [May 28, 2007, 8:00pm UTC](https://www.ruby-forum.com/t/randomize-array-content/105320/1 "2007-05-28T20:00:58Z")

</div>

Hello,

After 2 months working with ruby i still bump to some of those:

what would be the simplest way (couldn’t find a rand method) to  
achieve a subject’s task?

thanks!  
t

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [May 28, 2007, 8:08pm UTC](https://www.ruby-forum.com/t/randomize-array-content/105320/2 "2007-05-28T20:08:12Z")

</div>

removed\_email\_address@domain.invalid wrote:

> Hello,
> 
> After 2 months working with ruby i still bump to some of those:
> 
> what would be the simplest way (couldn’t find a rand method) to  
> achieve a subject’s task?
> 
> thanks!  
> t

ary.sort\_by { rand }

Regards  
Stefan

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [May 28, 2007, 8:09pm UTC](https://www.ruby-forum.com/t/randomize-array-content/105320/3 "2007-05-28T20:09:00Z")

</div>

removed\_email\_address@domain.invalid wrote:

> Hello,
> 
> After 2 months working with ruby i still bump to some of those:
> 
> what would be the simplest way (couldn’t find a rand method) to  
> achieve a subject’s task?

If you mean that you want to shuffle the array, then:

array.sort\_by{rand}

This comes up often enough that it’d almost be worth adding an  
Array#shuffle (and/or #shuffle!) method to core…

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [May 28, 2007, 8:51pm UTC](https://www.ruby-forum.com/t/randomize-array-content/105320/4 "2007-05-28T20:51:04Z")

</div>

On May 28, 2:07 pm, Alex Y. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> array.sort\_by{rand}
> 
> This comes up often enough that it’d almost be worth adding an  
> Array#shuffle (and/or #shuffle!) method to core…
> 
> –  
> Alex

Thanks Alex, that would be it!

best  
t
