sort_by{rand} doesn't shuffle array

P

Pat Maddox

I did some searching on how to shuffle an array, and found
sort_by{rand}. However, if I call it, it doesn't make a change to my
array at all. I've got a class like this
class MyClass
def initialize
# Populate the array
@my_array =3D Array.new
...
end

def shuffle!
@my_array.sort_by{rand}
end
end

If I call shuffle! from my code, the array's elements are still in the
order that they were created. Why are they not being shuffled like I
want?
 
S

Sylvain Joyeux

or @my_array.sort_by! { rand }
Except that sort_by! does not exist ;-) (at least not in 1.8.4)
 
M

Mauricio Fernandez

or @my_array.sort_by! { rand }

RUBY_RELEASE_DATE # => "2005-12-24"
RUBY_VERSION # => "1.8.4"
%w[a b c d].sort_by!{rand} # =>
# ~> -:3: undefined method `sort_by!' for ["a", "b", "c", "d"]:Array (NoMethodError)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,701
Latest member
XavierQ83

Latest Threads

Top