unexpected behavior with Array

4 views
Skip to first unread message

richardun

unread,
Dec 18, 2012, 11:50:44 AM12/18/12
to ru...@googlegroups.com
This is not so much a how but a why it was designed this way.  I know how to do it.

When you do this:

Array.new(3, obj)

you create an array with three elements of the same object, not a copy.

a = Array.new(3, Array.new(2, ''))

→ ['',''], ['',''], ['','']

Understandably, I might want to edit just a[1][0], but in this case, I'd actually edit all three arrays because it references the same given object, NOT a copy.  I know if I wanted a copy I could do this:

a = Array.new(3) { Array.new(2, '') }

But my question is, WHY would someone want to do the first one where you just have references to the same object?  How could this be useful?  If it's in the language, the Matz obviously saw a reason for it.  I just don't know what that is.

Thanks!
R


Reply all
Reply to author
Forward
0 new messages