From: dblack@... Date: 2006-08-29T10:46:58+09:00 Subject: Re: Should Array.new(n, obj) be deprecated? Hi -- On Tue, 29 Aug 2006, Jason Merrill wrote: > *Common Array Gotcha: > > If I want to make an array of 5 hashes, or of containers in general, > if I only skimmed the documentation, I might try to do > > menus = Array.new(6, Hash.new) > > Of course, the array is filled with a single instance of Hash, so if I do > > menus[0]['dessert'] = 'cake' > menus[1]['dessert'] = 'ice cream' > > puts menus[0]['dessert'] > => 'ice cream' > > This is because menus[0] and menus[1] actually refer to the same > object, and it's being overwritten in the second statement. > > What I meant to do was > > menus = Array.new(6) {Hash.new}, which executes the block once for > each slot in the array, thus producing 6 new instances of hash. I think everyone does this once or twice. It's one of the nuby rites of passage :-) I would put it in the category of "things that you might not think of spontaneously, but that make sense in relation to how the rest of Ruby works, once you see what they do." Those things should not, I think, be removed from the language; it's OK for Ruby to have *some* learning curve, and to be optimized for people who are planning to spend some time with it. The things I don't like are the ones in the category of "things that work a certain way without any evident basis in how the rest of Ruby works or in common-sense semantics." It's a small category (since Ruby is well-designed), but it includes, for example, instance_methods(true/false). David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org