[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

sort_by{rand} doesn't shuffle array

Pat Maddox

1/3/2006 10:04:00 AM

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 = 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?


4 Answers

Mauricio Fernández

1/3/2006 10:22:00 AM

0

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


Devin Mullins

1/3/2006 11:55:00 AM

0

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



Sylvain Joyeux

1/3/2006 12:09:00 PM

0

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


Mauricio Fernández

1/3/2006 12:12:00 PM

0

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