Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > sort_by{rand} doesn't shuffle array

Reply
Thread Tools

sort_by{rand} doesn't shuffle array

 
 
Pat Maddox
Guest
Posts: n/a
 
      01-03-2006
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?


 
Reply With Quote
 
 
 
 
Mauricio Fernandez
Guest
Posts: n/a
 
      01-03-2006
On Tue, Jan 03, 2006 at 07:03:42PM +0900, Pat Maddox wrote:
> def shuffle!
> @my_array.sort_by{rand}

@my_array = @my_array.sort_by{rand}
> end
> end


--
Mauricio Fernandez


 
Reply With Quote
 
 
 
 
Devin Mullins
Guest
Posts: n/a
 
      01-03-2006
Mauricio Fernandez wrote:

>On Tue, Jan 03, 2006 at 07:03:42PM +0900, Pat Maddox wrote:
>
>
>> def shuffle!
>> @my_array.sort_by{rand}
>>
>>

> @my_array = @my_array.sort_by{rand}
>
>

or @my_array.sort_by! { rand }

>> end
>>end
>>
>>




 
Reply With Quote
 
Sylvain Joyeux
Guest
Posts: n/a
 
      01-03-2006
> or @my_array.sort_by! { rand }
Except that sort_by! does not exist (at least not in 1.8.4)
--
Sylvain


 
Reply With Quote
 
Mauricio Fernandez
Guest
Posts: n/a
 
      01-03-2006
On Tue, Jan 03, 2006 at 08:54:33PM +0900, Devin Mullins wrote:
> Mauricio Fernandez wrote:
>
> >On Tue, Jan 03, 2006 at 07:03:42PM +0900, Pat Maddox wrote:
> >
> >
> >> def shuffle!
> >> @my_array.sort_by{rand}
> >>
> >>

> > @my_array = @my_array.sort_by{rand}
> >
> >

> 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)

--
Mauricio Fernandez


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Array.shuffle/Array.shuffle! Jeff Moore Ruby 6 10-09-2008 07:14 PM
Shuffle array elements (3 to end of array) in random order Tuxedo Javascript 8 05-07-2007 03:28 PM
Shuffle Array. bjorn2k@hotmail.com Ruby 6 06-14-2006 02:18 PM
Shuffle an array of integers. pieter_hordijk@hotmail.com Java 12 04-26-2005 05:31 AM
Array.shuffle()? James Edward Gray II Ruby 1 09-23-2004 08:46 AM



Advertisments