From: Rick DeNatale Date: 2009-03-30T01:54:53+09:00 Subject: Re: Is there an idiom for mass-populating Hash keys? --0016e64f51ae5e73b7046644d3f1 Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: quoted-printable On Sun, Mar 29, 2009 at 12:05 PM, Shot (Piotr Szotkowski) wrot= e: > Hello, good folk of ruby-talk. > > I was wondering whether there=92s a Ruby > idiom to mass-populate keys of a Hash. > > I=92m 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 =96 initially all nil: > > class Graph > def initialize enum > @vertices =3D {} > enum.each { |vertex| @vertices[vertex] =3D nil } > end > end > > Is there a more elegant way to take an enum > and turn it into nil-referencing Hash keys? > Why bother? The only reason I can thing of is that you want to use @vertices.keys to get the collection of vertices, but why be indirect. class Graph def initialize(enum) @vertices =3D enum @labels =3D {} end end @labels[anything] will return nil if anything isn't a key. --=20 Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale --0016e64f51ae5e73b7046644d3f1--