From: Daniel Schierbeck Date: 2006-07-28T18:35:09+09:00 Subject: Re: Creating hashes with duplicate keys Sy Ali wrote: > I want to simplify this hash creation: > g = { 1 => "test", 2 => "test", } > > I have a particularly complicated hash that I'm generating. It can > have very large values. > > Right now, I duplicate values with something like this: > > c = { 1 => "one", } > d = { 2 => c[1], } > c.merge!(d) > > however, I don't like the way my code looks.. I want to be able to > specify the duplication within the hash generation. > > Is this possible? This will work: hsh = Hash.new{|h, k| h[k] = (k == 1 ? "one" : h[k - 1])} Note that all the values will be the same -- the same object! If you want duplicates, do this instead: hsh = Hash.new{|h, k| h[k] = (k == 1 ? "one" : h[k - 1].dup)} Just ask if there are parts of the snippet you don't understand. Cheers, Daniel