Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Re: Is there an idiom for mass-populating Hash keys?
Rick DeNatale
3/29/2009 4:55:00 PM
On Sun, Mar 29, 2009 at 12:05 PM, Shot (Piotr Szotkowski) <shot@hot.pl>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.denh...
Twitter:
http://twitter.com/Ri...
WWR:
http://www.workingwithrails.com/person/9021-ric...
LinkedIn:
http://www.linkedin.com/in/ri...
2 Answers
Suraj Kurapati
3/30/2009 11:16:00 PM
0
Shot (Piotr Szotkowski) wrote:
> The catch is Iâ??ll be doing various things to this graph,
> like merging vertices together, grouping them by their labels (graph
> colouring), and doing similar operations on (labeled) edges.
Try providing a default_proc to Hash.new:
Hash.new {|h,k| h[k] = nil }
Now previously unregistered vertices will be registered upon hash access
(Hash#[]). To illustrate this technique, consider this "dynamic
programming" based Fibonacci sequence implementation:
fib = Hash.new {|h,k| k < 2 ? 1 : h[k-1] + h[k-2] }
p 0 => fib[0]
p 1 => fib[1]
p 5 => fib[5]
p :cache => fib
--
Posted via
http://www.ruby-...
.
Suraj Kurapati
3/30/2009 11:19:00 PM
0
Suraj Kurapati wrote:
> consider this "dynamic programming" based Fibonacci sequence implementation:
>
> fib = Hash.new {|h,k| k < 2 ? 1 : h[k-1] + h[k-2] }
Whoops, I forgot to store the computed value in the hash!
fib = Hash.new {|h,k| h[k] = k < 2 ? 1 : h[k-1] + h[k-2] }
Now it should work. Sigh :-)
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: Is there an idiom for mass-populating Hash keys?
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password