From: "Wolfgang Nádasi-Donner" Date: 2007-01-25T21:00:10+09:00 Subject: Re: Array and instance variable problem? Maxime Guilbot schrieb: > What I meant in my second message, is that when @indexes is a FixNum > (not an Array). > This code is working as expected: In the code def get_next @indexes[0] = @indexes[0]*2 @indexes[1] = @indexes[1]*2 @indexes end the contents of "@indexes" will be changed, but the "Array" object will be the same. In def get_next @indexes = @indexes*2 @indexes end "@indexes*2" will create a new object, which will be assigned to "@indexes" afterwards. Conclusion: in case of the Array object you will end with the same object with changed contents (the same is valid for Hash objects, and may be valid for strings - see below), in case of the Fixnum object a new object will be created and referenced. An example for class String to clarify this. >>>>> Code >>>>> require 'pp' class Dummy def initialize @indexes = "a" end def get_next @indexes[0,1] = @indexes[0,1].succ @indexes end def get_next_10 all = [] for i in 0..9 all << get_next end all end def show_id puts @indexes.object_id end end d = Dummy.new x = d.get_next_10 puts '##### show contents #####' pp x puts '##### show @indexes-id #####' d.show_id puts '##### show ids of Array elements #####' x.each{|e|puts e.object_id} >>>>> Output >>>>> ##### show contents ##### ["k", "k", "k", "k", "k", "k", "k", "k", "k", "k"] ##### show @indexes-id ##### 24861400 ##### show ids of Array elements ##### 24861400 24861400 24861400 24861400 24861400 24861400 24861400 24861400 24861400 24861400 >>>>> EoE >>>>> If you change a line of code a little bit, something completely different will happen. >>>>> Parts of Code >>>>> def get_next # @indexes[0,1] = @indexes[0,1].succ @indexes = @indexes.succ # <<<<<< Here is the minor change @indexes end >>>>> Output >>>>> ##### show contents ##### ["b", "c", "d", "e", "f", "g", "h", "i", "j", "k"] ##### show @indexes-id ##### 24861380 ##### show ids of Array elements ##### 24861470 24861460 24861450 24861440 24861430 24861420 24861410 24861400 24861390 24861380 >>>>> EoE >>>>> Wolfgang Nádasi-Donner