First day newbie question re. Missing hash key (key error)

Trying to write a unique word counting program as my first exercise, trying to store occurrences per word in a hash while iterating over my array of ‘words’:


dict = {} of String => Int32
word_array.each do |word|
dict[word] += 1

gives me

Missing hash key: “a” (key error)
where “a” happens to be the first word in the array

What am I doing wrong? Also, if you see me doing something non-idiomatic, please do correct me. Much appreciated!

Pretty sure the problem is dict[word] += 1 is shorthand for dict[word] = dict[word] + 1, but since this is the first time that word has been seen, it does not currently exist in the hash. Hence you get an error when trying to access that key. For this case, I’d prob use Hash(K, V) - Crystal 1.11.2 as a way of giving a hash key a default value of 0.

Technically are over-complicating this. Can really just do word_array.tally and be done with it :stuck_out_tongue:.

ref: Enumerable(T) - Crystal 1.11.2

Thanks much! Will have a look @ tally now …

If it’s purely for the learning experience, try doing it yourself first, and see if you get the same result as tally. Maybe the source text has the same words with different casing, how to handle that?

Maybe the source text has the same words with different casing, how to handle that?

We can use tally_by { … } :grin:

2 Likes

Don’t give it all away, give them a chance to learn to read the stdlib documentation. :grin:

2 Likes