How to randomly shuffle an Array in Ruby?

3

I'd like to have the items in an array shuffled. Something like this:

[1,2,3,4].scramble => [2,1,3,4]
[1,2,3,4].scramble => [3,1,2,4]
[1,2,3,4].scramble => [4,2,3,1]

and so on, randomly. How to do?

    
asked by anonymous 10.08.2014 / 04:28

1 answer

4

You can use the sample method to pass the quantity you want to return, or have the shuffle, follow an example:

array = [1,2,3,4]

#shuffle
>> array.shuffle
=> [4, 1, 2, 3]

#sample
>> array.sample(array.length)
=> [3, 1, 2, 4]
>> array.sample(array.length)
=> [2, 4, 1, 3]

I hope I have helped:)

    
12.08.2014 / 18:32