From: Perry Smith Date: 2007-08-02T13:43:05+09:00 Subject: Re: change method Array.new? (Was: Unexpected behavior with Armin Armbruster wrote: > unknown wrote: >> Hi -- >> >> >> Think of it as a rite of passage :-) Sort of like realizing that: >> >> array.each {|a| puts a } >> >> can be written as: >> >> puts array >> >> or that ^ and $ operate per line rather than per string in regular >> expressions. >> >> >> David > > I have no problem with Array.new(size, obj), in fact I think it is a > syntactically nice form. What I have a problem with is that it behaves > differently, depending what the object is. > >> a = Array.new(3,0) > => [0, 0, 0] >> a[1] = 1 > => 1 >> a > => [0, 1, 0] > >> b = Array.new(3,[]) > => [[], [], []] >> b[1] << 1 > => [1] >> b > => [[1], [1], [1]] > >> c = [[],[],[]] > => [[], [], []] >> c[1] << 1 > => [1] >> c > => [[], [1], []] > > > Why can't b behave like a in this case This seems really obvious to me and it must seem really non-obvious to you. Interesting (I think). The second form creates an array. Each element in that array is a pointer (this is how I think of it at least) to the same array -- lets call it b. You put something into b, and you will see it from each of the pointers to b. In the first example, if you could put a tag on the 1 (somehow) or, like in lisp, if you could put a property on it. Then it too would show up in all three views of that object. Oh, how about this: In the b example, instead of: b[1] << 1 (which adds an element to b), you need to replace the second element: irb(main):003:0> b = Array.new(3, []) => [[], [], []] irb(main):004:0> b[1] = [ 1 ] => [1] irb(main):005:0> b => [[], [1], []] irb(main):006:0> Does any of that help? -- Posted via http://www.ruby-forum.com/.