Iteration and Array to Hash conversion


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-693PD/0/8?curriculum_id=5059f8619189a5000201fbcb


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 = Hash.new (0)

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

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
end

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.


#2

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.


#3

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.


#4

@jekabs,
You could read this linked article
https://discuss.codecademy.com/t/5-iterating-over-the-array/34206/2?u=leonhard.wettengmx.n


#5

Thanks that helps as well.

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