From: Gary Wright Date: 2010-09-09T07:38:25+09:00 Subject: Re: Problem with Hash of Arrays On Sep 8, 2010, at 5:25 PM, Fearless Fool wrote: > > 1: sentence = ParserModule.parse(string) > 2. if sentence.has_key?(:preposition) > 3. p = sentence[:preposition] > ... > > ... I'll sic the DRY police on you. :) It seems to me you've described two mutually contradictory 'patterns': -- a hash that defaults to a new array when a key is referenced -- a hash that is queried 'randomly' (as in individual keys are accessed by name rather than all the entries being processed similarly). You claim that the combination is bad because the 'state' of the hash changes as a side effect of the queries. These two patterns don't seem to go together. The first suggests that the hash is a named collection of arrays but the second suggests that the hash values are not homogeneous and that sometimes you don't want an array as the default value. As I pointed out, you can always override the hash default on a per 'lookup' basis to avoid the problem you are complaining about: if prep = sentence.fetch(:preposition, nil) # do something with prep end nouns.sentence.fetch(:nouns, []).each { |n| process_noun(n) } process_all_verbs(sentence[:verbs]) # if you don't care if this creates an empty entry for :verbs Another solution would be to not use a Hash that defaults to an Array. In that case you could still use 'fetch' to change the behavior on each individual access when you really do want an array installed. sentence.fetch(:nouns) { |miss| sentence[miss] = [] } Gary Wright