Proposal: Array#to_h, to simplify hash generation

I were too quick to say that is was important. Of cause you supply another
concat method to #into in order to avoid overwriting earlier entries.

untestted :slight_smile:

class Hash
def myappend(data)
key, value = data
self[key] += value
end
end

[1, “2”, 3].into(Hash.new(Array.new), myappend) {|i| [i.class, i]}

{“Fixnum”=>[1, 2], “String”=>[“2”]}

Sorry :slight_smile:

···

On Tue, 22 Jul 2003 06:59:13 +0900, Brian Candler wrote:

On Tue, Jul 22, 2003 at 05:46:35AM +0900, Simon Strandgaard wrote:

Important: Hash#append should not overwrite earlier entries.

Hmm. What should it do then? Raise an exception? h1.update(h2) will
overwrite corresponding keys in h1, so there is a precedent for collect_into
working in that way.

I would rule out, say, automatically promoting a value into an array. It’s
too application-specific. If your application does in fact hold a hash of
arrays, then I think you’d code your append method accordingly; in other
cases, the structure may be different (a hash of hashes, say), in which case
the append method is different.


Simon Strandgaard