Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly sort (scramble) an array in Ruby?

I'd like to have my array items scrambled. 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

like image 369
Daniel Cukier Avatar asked Nov 29 '09 18:11

Daniel Cukier


People also ask

How to sort an array in Ruby?

Learn to Use the Sort & Sort! Ruby Methods The most basic form of sorting is provided by the Ruby sort method, which is defined by the Enumerable module. Notice that sort will return a new array with the results.

How to sort hashes in Ruby?

How to Sort Hashes in Ruby. You are not limited to sorting arrays, you can also sort a hash. Example: hash = {coconut: 200, orange: 50, bacon: 100} hash.sort_by(&:last) # 50], [:bacon, 100], [:coconut, 200 This will sort by value, but notice something interesting here, what you get back is not a hash.

How do I randomize an array using the shuffle command?

the shuffle command returns a randomized version of an array and if you want to randomize in place, you can just write @number.shuffle! Show activity on this post.

What is the sort_by method in Python?

Well, the sort_by method expects a numerical value, that’s why length works. If you understand this, then you can use this method to do cool things, like sorting words that start with a capital letter & leaving everything else in place. def sort_by_capital_word (text) text .split .sort_by { |w| w [0].match?


1 Answers

Built in now:

[1,2,3,4].shuffle => [2, 1, 3, 4] [1,2,3,4].shuffle => [1, 3, 2, 4] 
like image 191
Ron Gejman Avatar answered Sep 19 '22 09:09

Ron Gejman