Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #2722
| From | Tom Reilly <w3gat@nwlagardener.org> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: hash of arrays |
| Date | 2011-04-12 20:52 -0500 |
| Organization | Service de news de lacave.net |
| Message-ID | <4DA501E3.3060103@nwlagardener.org> (permalink) |
| References | <17ed4aba89dcdda100deb6592ec4f9f5@ruby-forum.com> |
Define hash of hashes this way
#Using a default hash.
foo = Hash.new { |hash, key| hash[key] = Hash.new }
foo["a"][1] = "one"
foo["a"][2] = "a two"
foo["b"][3] = "b three"
foo["a"][4] = "b four"
p foo["a"][1]
p foo["a"][4]
p foo["a"].size
foo["a"].each {|x,y| p "#{x} #{y}"}
David Sprague wrote:
> I'm wrote this code to bin a list of words by word-length:
>
> dict = Hash.new([])
>
> dict_file.each do |line|
> line.chomp!()
> dict[line.length]<< line
> end
>
> expecting that I could avoid testing each time whether this was a new
> entry in the hash or not by just appending to the default, an empty
> array,
> if it is new.
>
> What happens is that the *same* array is assigned as the default value
> to all new entries so that all the hash entries finish with the same
> array of values.
>
> is there away to void having to write something like:
>
> if dict.key?(line.length)
> dict[line.length]<< line
> else
> dict[line.length] = line
> end
>
> or the ternary equivalent in the inner loop?
>
> thanks,
>
> Dave
>
>
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
hash of arrays David Sprague <david.sprague@gmail.com> - 2011-04-12 20:06 -0500
Re: hash of arrays Roger Braun <roger@rogerbraun.net> - 2011-04-12 20:27 -0500
Re: hash of arrays Roger Braun <roger@rogerbraun.net> - 2011-04-12 20:57 -0500
Re: hash of arrays Tom Reilly <w3gat@nwlagardener.org> - 2011-04-12 20:52 -0500
Re: hash of arrays jake kaiden <jakekaiden@yahoo.com> - 2011-04-12 22:05 -0500
Re: hash of arrays botp <botpena@gmail.com> - 2011-04-12 22:05 -0500
Re: hash of arrays "WJ" <w_a_x_man@yahoo.com> - 2011-04-17 16:37 +0000
csiph-web