Object assignment and pointers

前端 未结 4 2003
予麋鹿
予麋鹿 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-10 18:09

    You never deal with a copy. It's the same object in memory, but you just declare 2 references to it: in your first example: bar and beans point towards the same object in memory; and in your second example: foo and baz point to the same array in memory initially.

    Check out the 2 picture/drawings, in the Java tutorial page that explains the mechanism (it's the same as in Ruby) and those 2 pictures only, worth more than any explanation in words: http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 18:15

    Basicly ruby is using reference pointer so when you are changing one thing other is also get effected.

    0 讨论(0)
提交回复
热议问题