什么是'input = self'和'input = self.dup'之间的区别

时间:2013-09-07 22:05:25

标签: ruby arrays self

所以我遇到的问题是理解= self= self dup之间的区别。当我运行下面的代码时,我放入的任何数组都会被永久更改。

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

但后来我注意到,如果我放input = self.dup它不会永久改变我的数组。有人可以解释原因吗?谢谢!

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

3 个答案:

答案 0 :(得分:2)

通过说object_idself是2个不同的对象,检查他们的self#dup会给你答案。

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]

答案 1 :(得分:0)

因为self.dup返回数组的浅表副本,因此代码不会永久更改数组。

Reference

答案 2 :(得分:0)

当您复制数组时,最终会得到两个具有相同元素的独立数组,如下例所示:

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

x << 4
p x
p y

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

您不希望x数组的更改会影响y数组,不是吗?类似地:

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"]

在该示例中,arr扮演self的角色,而copy扮演self.dup的角色。数组self和self.dup是不同的数组,恰好具有相同的元素。

数组可以包含无限数量的引用它的变量:

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

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

现在让我们让输入引用另一个数组:

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]