Forum: Ruby sort_by{rand} doesn't shuffle array

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2006-01-03 11:03
(Received via mailing list)
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?
Dd76a12d66f843de5c5f8782668e7127?d=identicon&s=25 Mauricio Fernandez (Guest)
on 2006-01-03 11:25
(Received via mailing list)
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}
918c6daad03c85e51ad1a11f57017947?d=identicon&s=25 Devin Mullins (Guest)
on 2006-01-03 12:55
(Received via mailing list)
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 }
934180817a3765d132193a5428f99051?d=identicon&s=25 Sylvain Joyeux (Guest)
on 2006-01-03 13:11
(Received via mailing list)
> or      @my_array.sort_by! { rand }
Except that sort_by! does not exist ;-) (at least not in 1.8.4)
Dd76a12d66f843de5c5f8782668e7127?d=identicon&s=25 Mauricio Fernandez (Guest)
on 2006-01-03 13:14
(Received via mailing list)
On Tue, Jan 03, 2006 at 08:54:33PM +0900, Devin Mullins wrote:
> >
> >
> 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)
918c6daad03c85e51ad1a11f57017947?d=identicon&s=25 Devin Mullins (Guest)
on 2006-01-03 13:23
(Received via mailing list)
Mauricio Fernandez wrote:

># ~> -:3: undefined method `sort_by!' for ["a", "b", "c", "d"]:Array (NoMethodError)
>
>
3.times { Hand.smack!(Head) }
This topic is locked and can not be replied to.