David S. 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