On 7/31/07, Armin Armbruster <aarmbruster / ndigital.com> wrote: > > Frankly, just as the poster in ruby-talk I have my troubles accepting > this not being a violation of the principle of least surprise (and yes, > I come from a C programming background). > Anyhow, now I know it and (hopefully) will remember it the next time. I > still have not glue why one would want an array whose elements are > referencing the same object. Does anybody know an example where this is > actually useful? > In ruby, constructing an array and adding the same object multiple times is the least surprising behavior. Creating several copies of the object would be "hidden behavior" inside the array initializer, and hidden behavior is usually a bad thing. The hidden behavior would force all objects to have valid dup/clone methods (which is not the case for Fixnum). As an example consider creating an array of classes using some default class. The problem here is that we now have several clones of the default class that are independent of the original. Adding new methods to the default class is not reflected in the clones. The current implementation of Array allows the user to choose how objects are populated in the array. The user can explicitly use the same object, or the user can create duplicates or new objects per index using the block format of the initializer. Each form is explicit which is why the implementation adheres the principle of least surprise. Blessings, TwP