Iteration and Array to Hash conversion


Hey. I completed the excercise but it would be great if someone could clear some things up for me.

print "This is sooooo eaaaasyyyy."
text = gets.chomp # lets assume I typed "uno dos dos tres tres tres"
puts text
words = text.split

frequencies = (0)

words.each do |word|
    frequencies [word] += 1

Firstly, some suggest adding (" ") after the text.split, yet it does not seem to matter.

Secondly, about the hashes. The default value is 0 and as I understand this "0" is assigned when a non-existant key is requested.
"uno" exists and has been typed once, so its value before iteration should be "1", and after iteration "2", no? Instead, after iteration it is 1.

Thirdly, how does the user input suddently, from an Array, change to being a part of the Hash in this code?

words.each do |word|
    frequencies [word] += 1

Is it that "frequencies [word] +=1" both iterates and sorta converts the data-type at the same type? Before that, frequencies was just an empty Hash.


Hello @jekabs,

I will be happy to help you! To answer all of your questions, in order.

1) Adding (" ") after text.split tells it to split it every time it encounters a space. This doesn't seem to make a difference though, because when no arguments are passed into the .split method, it takes " " as default.

2) Secondly, when you set a default value of a new Hash, it has no keys, and will always return 0 when called with a key. "uno" doesn't exist yet in the Hash because we haven't specified it to exist. Right now, frequencies is just an empty Hash.

3) The user input is always an array, it never becomes a "part" of the Hash. In this .each loop, we tell the loop to loop over the words array, which contains the words in the user's input. So, every time it iterates, it adds the value of 1 to the current value that the word holds in the Hash (which is 0). So, first time it goes through, it assigns the value of 1 to frequencies["uno"]. Then, it assigns the value of 1, then 2 to frequencies["dos"] and so on and so forth until the end of the words array.

I hope this clears out any doubts you have had with this exercise. If you feel my solution is satisfactory, don't be afraid to put it as the solution, as it will also notify others that this topic is closed.


The two bold parts seem contradictory to me. You say that the words hold a value in the hash, yet never become a part of it?
Thanks a lot for helping btw.


You could read this linked article


Thanks that helps as well.

Kek, You both have provided the solutions but I cannae give you both a tick.