From: Dan Zwell Date: 2007-08-01T04:15:03+09:00 Subject: Re: Unexpected behavior with multidimensional arrays Tim Pease wrote: > On 7/31/07, Armin Armbruster 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. > I agree with you on this point. However, I can't think of a situation where the second argument is useful. For example, ary = Array.new(n, 0) can be replaced with ary = Array.new(n) {0} So I ask, is this functionality (creating an array with 2 arguments) useful to people? Because I think everybody makes this mistake once, and that certainly seems to qualify as being counter-intuitive. In fact, anything that in done with Array.new(n, obj) can be done with Array.new(n) {obj}. Am I mistaken? See the following: >> inner = [] => [] >> ary = Array.new(3) {inner} => [[], [], []] >> inner << "hi" => ["hi"] >> ary => [["hi"], ["hi"], ["hi"]] The above does the same thing as ary = Array.new(3, []), but needs one more line of code. What does everyone think? Dan