From: MenTaLguY Date: 2008-02-23T08:51:13+09:00 Subject: Re: ||= [] idiom On Sat, 23 Feb 2008 07:27:17 +0900, "Robert Klemme" wrote: > But all these points you mention do also apply to the Hash based > approach. You can even use the same wording, if you like: > > @category_for = Hash.new {|h, tag| h[tag] = []} Yes. I was thinking in terms of why to do the refactoring at all, using my example refactoring as a point of reference, rather than weighing the pros and cons of different refactorings of the original code. > I was expecting reasoning that would highlight advantages of using a > method here. The only thing that comes to mind is that if you want to > exchange the implementation altogether, then a method based approach > is better. But in that case you'd probably do > > def add_to_category(tag, item) > (@cat[tag] ||= []) << item > end > > Because that abstracts away category creation *and* adding to the > structure. This is a good point; I would prefer add_to_category to just category_for. > On the flipside, for small scripts that Hash based approach has the > advantage of being shorter (because no method is needed). True, though shorter isn't necessarily clearer. One of the disadvantages of using default blocks for hashes is the additional cognitive burden when reading the code: you must keep in the back of your mind that that, "this hash, it is a hash unlike any other." I don't think that's a significant issue for small scripts, but it is why I tend to avoid the use of default blocks in larger scripts and libraries. -mental