From: "ara.t.howard" Date: 2009-03-30T01:15:35+09:00 Subject: Re: Is there an idiom for mass-populating Hash keys? On Mar 29, 2009, at 10:05 AM, Shot (Piotr Szotkowski) wrote: > Hello, good folk of ruby-talk. > > I was wondering whether there’s a Ruby > idiom to mass-populate keys of a Hash. > > I’m coding a graph class supporting labeled vertices, and I want to > represent this relationship as a @vertices Hash, with keys being the > actual vertices and values being their labels – initially all nil: > > class Graph > def initialize enum > @vertices = {} > enum.each { |vertex| @vertices[vertex] = nil } > end > end > > Is there a more elegant way to take an enum > and turn it into nil-referencing Hash keys? dunno if it's really better but this is one approach: cfp:~ > cat a.rb hash = {} enum = ('a'..'z') hash.update Hash[*enum.zip([])] p hash cfp:~ > ruby a.rb {["e", nil]=>["f", nil], ["o", nil]=>["p", nil], ["y", nil]=>["z", nil], ["i", nil]=>["j", nil], ["s", nil]=>["t", nil], ["c", nil]=>["d", nil], ["m", nil]=>["n", nil], ["w", nil]=>["x", nil], ["g", nil]=>["h", nil], ["q", nil]=>["r", nil], ["a", nil]=>["b", nil], ["k", nil]=>["l", nil], ["u", nil]=>["v", nil]} a @ http://codeforpeople.com/ -- we can deny everything, except that we have the possibility of being better. simply reflect on that. h.h. the 14th dalai lama