Ruby 如果 object member 是 Array or Hash 该 return reference or clone

shewer · May 12, 2019 · 3272 hits

请问各位 像 Array Hash 有太多改变内容的 method 是 return reference or clone(dup)

class A
  attr_reader :data
  def initialize(array)
    @data=array
  end
end

a=A.new([1,2,3,4])
b=a.data     #   b == @data 
b.append 66  # b[1,2,3,4,66]    a.data [1,2,3,4,66]
p b  #[1, 2, 3, 4, 66]
p a  # #<A:0x00007fffd00eef98 @data=[1, 2, 3, 4, 66]>

=


No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.