I don't understand this line in my program


#1


puts " Input a Number: "
text = gets.chomp

words = text.split (" ")

frequencies = Hash.new (0)

words.each { |x| frequencies[x] += 1 }

frequencies = frequencies.sort_by { | a, b | b}

frequencies.reverse!


I copied this code becouse i couldn't finish mine correctly, but i don't understand one line in this code

words.each { |x| frequencies[x] += 1 }

If someone could explain me in particular how this works?
Thanks.


Replace this line with your code.


#2

You might want to write your code in the longer do...end format to make it easier to wrap your head around for awhile.

The line

words.each { |x| frequencies[x] += 1 }

can be written like this instead (I'm going to replace x with word so it is easier to follow)

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

What is happening is...
words.each do |word|
For each of the words, do the following code, and refer to the current word as word

frequencies[word] += 1
Look in our frequencies hash (maybe think dictionary or map), and see if the word currently assigned to word exists.
If it does not exist, add it, with a starting value of 0. Now that we know it exists, add 1 to it.

So imagine you had a string "I like the chocolate and the cookies"
We would break it into an array words. For each word we want see if frequencies already has an entry for that word, and increase it's counter by 1. In the example above, when you get to the first 'the', it wouldn't exist, so you would add it, and increment it by 1. When you get to the next 'the' it would already exist in the hash, and you would increase the 1 to a 2. In the end, all your words would be shown with a count of 1, except 'the', which would have 2.


#3

Wow, thank you @chipcoder02347 for explaining me in detail how this works. I'm learning Ruby for a few days with not so good programming background so i kinda get stuck on something that isn't even hard so much. It will take me some time to adapt and get used to it. However, problems like these won't stop me to get better and better each day. Thanks again! Appreciate it.


#4

Great mindset. Good luck on your journey and keep asking questions


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.