Forum: Ruby what is dup?

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.
5ef95bf95af5064ff3c2bcafa6a8a212?d=identicon&s=25 David Madden (Guest)
on 2007-01-16 18:26
(Received via mailing list)
I am playing with an example in the ruby cookbook where  a shuffle
function is added to the array class:

class Array

   def shuffle!
     each_index do |i|
       j = rand(length-i) + i
       self[j], self[i] = self[i], self[j]
     end
   end

   def shuffle
     dup.shuffle!
   end

end

What I don't understand is the line "dup.shuffle!"

What is the dup object?

Dave.
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2007-01-16 18:32
(Received via mailing list)
On 1/16/07, David Madden <moose56@gmail.com> wrote:
>    end
>
dup returns a copy (duplicate) of the object. In the above code, it is
used to let you get back a shuffled copy of the Array, without
shuffling the original.

type:
ri Object#dup
for more info.
D29b5f59a4c6f8a8722cb9c93a01d311?d=identicon&s=25 Tamreen Khan (Guest)
on 2007-01-16 20:17
(Received via mailing list)
On 1/16/07, Wilson Bilkovich <wilsonb@gmail.com> wrote:
> >        self[j], self[i] = self[i], self[j]
> >
> > What is the dup object?
> >
>


I think a wordier but equivalent way of doing that is:
>
return self.dup.shuffle!

That just means "duplicate myself, shuffle the duplicate, then return
it."
5ef95bf95af5064ff3c2bcafa6a8a212?d=identicon&s=25 David Madden (Guest)
on 2007-01-16 20:31
(Received via mailing list)
>>
>
> dup returns a copy (duplicate) of the object. In the above code, it is
> used to let you get back a shuffled copy of the Array, without
> shuffling the original.
>
> type:
> ri Object#dup
> for more info.
>

Thanks,

Dave.
This topic is locked and can not be replied to.