[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

what is dup?

David Madden

1/16/2007 5:26:00 PM

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.

2 Answers

Wilson Bilkovich

1/16/2007 5:33:00 PM

0

On 1/16/07, David Madden <moose56@gmail.com> wrote:
> 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?
>

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.

David Madden

1/16/2007 7:30:00 PM

0

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