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


Groups > comp.lang.ruby > #2725

Re: hash of arrays

From jake kaiden <jakekaiden@yahoo.com>
Newsgroups comp.lang.ruby
Subject Re: hash of arrays
Date 2011-04-12 22:05 -0500
Organization Service de news de lacave.net
Message-ID <0f5f3ec73bfb62bbcb3e566d55e16e48@ruby-forum.com> (permalink)
References <17ed4aba89dcdda100deb6592ec4f9f5@ruby-forum.com>

Show all headers | View raw


David Sprague wrote in post #992397:
> I'm wrote this code to bin a list of words by word-length:

hi david,
  if you're just trying to group words by their length, i'm not sure why
you need a hash of arrays, a simple hash would do...

list = %W[a cd def ghi jklm]
hash = {}
list.collect{|entry| hash[entry.length] = entry}
p hash

=> {1=>"a", 2=>"cd", 3=>"ghi", 4=>"jklm"}

  the problem here is that any words of the same length would result in
only one key (the last one) having the value of the word.  you could
just switch, and use the word as the key, and the length as the value...

list.collect{|entry| hash[entry] = entry.length}

=> {"cd"=>2, "a"=>1, "jklm"=>4, "def"=>3, "ghi"=>3}

  but of course if you repeat words, you'll have the same problem.  the
quickest (and probably dumbest) solution i can think of is adding some
kind of "unique id" to each key, so that they don't get lost -

list = %W[a cd def ghi jklm]
hash = {}
uniqueID = 0
x = 0
while x < list.length
  hash ["#{list[x].length}.#{uniqueID}"] = list[x]
  x += 1
  uniqueID += 1
end
hash.sort.each{|k, v| p "#{k}, #{v}"}

=>"1.0, a"
  "2.1, cd"
  "3.2, def"
  "3.3, ghi"
  "4.4, jklm"

  you could then call a String#split (or something better and easier,
i'm winging it here,) on the keys, to get all the words that are 3
letters long, etc...

  hashes of arrays certainly are cool though, and it might be fun to
play with them...

foo = Hash.new{|key, value| key[value] = []}

foo ["rays"] = %W[alpha beta gamma]
foo ["planets"] = %W[mercury venus earth mars]
foo ["colors"] = %W[red orange yellow green blue indigo violet]

p foo
p foo.length
p foo ["rays"][1]
p foo ["planets"][-1]
p foo ["colors"].length

 -j

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

Back to comp.lang.ruby | Previous | NextPrevious in thread | Next 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