Object assignment and pointers

前端 未结 4 2005
予麋鹿
予麋鹿 2020-12-10 17:56

I am a little confused about object assignment and pointers in Ruby, and coded up this snippet to test my assumptions.

class Foo
    attr_accessor :one, :two         


        
4条回答
  •  Happy的楠姐
    2020-12-10 18:01

    + and - in Array each return new arrays filled with the respective content, so foo += [...] not affecting baz is normal. Try the << operator on foo and the result will be baz seeing the same change.

    I'm not sure how Ruby handles the other thing internally but you might try using one.clone and two.clone in Foo#initialize.

提交回复
热议问题