Object assignment and pointers

前端 未结 4 2012
予麋鹿
予麋鹿 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条回答
  •  猫巷女王i
    2020-12-10 18:11

    There are a lot of questions in this question. The main thing to know is assignment never makes a copy in ruby, but methods often return new objects instead of modifying existing objects. For immutable objects like Fixnums, you can ignore this, but for objects like arrays or Foo instances, to make a copy you must do bar.dup.

    As for the array example, foo += is not concatenating onto the array stored in foo, to do that you would do foo.concat(['a']). Instead, it is making a new array and assigning foo to that. The documentation for the Array class mentions which methods mutate the array in place and which return a new array.

提交回复
热议问题