Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #2715

hash of arrays

From David Sprague <david.sprague@gmail.com>
Newsgroups comp.lang.ruby
Subject hash of arrays
Date 2011-04-12 20:06 -0500
Organization Service de news de lacave.net
Message-ID <17ed4aba89dcdda100deb6592ec4f9f5@ruby-forum.com> (permalink)

Show all headers | View raw


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

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | NextNext in thread | Find similar | Unroll thread


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