[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Is there an idiom for mass-populating Hash keys?

ara.t.howard

3/29/2009 4:16:00 PM


On Mar 29, 2009, at 10:05 AM, Shot (Piotr Szotkowski) wrote:

> 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?

dunno if it's really better but this is one approach:

cfp:~ > cat a.rb

hash =3D {}

enum =3D ('a'..'z')

hash.update Hash[*enum.zip([])]

p hash
cfp:~ > ruby a.rb
{["e", nil]=3D>["f", nil], ["o", nil]=3D>["p", nil], ["y", nil]=3D>["z", =
=20
nil], ["i", nil]=3D>["j", nil], ["s", nil]=3D>["t", nil], ["c", =20
nil]=3D>["d", nil], ["m", nil]=3D>["n", nil], ["w", nil]=3D>["x", nil], =20=

["g", nil]=3D>["h", nil], ["q", nil]=3D>["r", nil], ["a", nil]=3D>["b", =20=

nil], ["k", nil]=3D>["l", nil], ["u", nil]=3D>["v", nil]}




a @ http://codeforp...
--
we can deny everything, except that we have the possibility of being =20
better. simply reflect on that.
h.h. the 14th dalai lama