Question

So the problem I'm having is understanding the difference between = self and = self dup. When I run the code below any array I put into it is permanently changed.

class Array
  def pad(min_size, value = nil)
    input = self
    counter = min_size.to_i - self.length.to_i
    counter.times do
      input.push(value)
    end
    input
  end
end

But then I noticed if I put input = self.dup it would not permanently change my array. Can someone explain why? Thanks!

class Array
  def pad(min_size, value = nil)
    input = self.dup
    counter = min_size.to_i - self.length.to_i
    counter.times do
        input.push(value)
    end
    input
  end
end
Was it helpful?

Solution

Check their object_id which will give you answer,by saying that self and self#dup are 2 different object.

class Array
  def dummy
    [self.object_id,self.dup.object_id]
  end
  def add
    [self.push(5),self.dup.push(5)]
  end 
end

a = [12,11]
a.dummy # => [80922410, 80922400]
a.add # => [[12, 11, 5], [12, 11, 5, 5]]
a # => [12, 11, 5]

OTHER TIPS

Because self.dup returns a shallow copy of the array and so the code will not change the array permanently.

Reference

When you made a duplicate of your array, you ended up with two separate arrays that had the same elements in them, like in this example:

x = [1, 2, 3]
y = [1, 2, 3]

x << 4
p x
p y

--output:--
[1, 2, 3, 4]
[1, 2, 3]

You wouldn't expect changes to the x array to affect the y array, would you? Similarly:

arr = [1, 2, 3]
puts "arr = #{arr}"     #arr = [1, 2, 3

copy = arr.dup
puts "copy = #{copy}"   #copy = [1, 2, 3]

arr << 4
puts "arr = #{arr}"     #arr = [1, 2, 3, 4]
puts "copy = #{copy}"   #copy = [1, 2, 3]

copy << "hello"
puts "arr = #{arr}"     #arr = [1, 2, 3, 4]
puts "copy = #{copy}"   #copy = [1, 2, 3, "hello"]

In that example, arr plays the role of self, and copy plays the role of self.dup. The arrays self and self.dup are different arrays which happen to have the same elements.

An array can have an unlimited number of variables that refer to it:

arr = [1, 2, 3]
puts "arr = #{arr}"    #arr = [1, 2, 3]

input = arr
input << 4
puts "arr = #{arr}"    #arr = [1, 2, 3, 4]

Now let's make input refer to another array:

copy = arr.dup
input = copy
input << "hello"

puts "copy = #{copy}"    #copy = [1, 2, 3, 4, "hello"]
puts "input = #{input}"  #input = [1, 2, 3, 4, "hello"]
puts "arr = #{arr}"      #arr = [1, 2, 3, 4]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top