What is dup?

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.

On 1/16/07, David M. [email protected] 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.

On 1/16/07, Wilson B. [email protected] 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.”

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs