Frequencies[word] (Have answer correct, but would like to understand it)


This assignment is for Iterating over the Array.

I have the answer correct, but I just want to know why you write:

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

as opposed to

words.each { |word| puts word += 1 }

I have included the full answer below. Any explanation would be great!

puts "Insert text: "
    text = gets.chomp

words = text.split(" ")

frequencies =

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

  1. Your idea

words.each { |word| puts word += 1 }

doesn't convert Fixnum.


frequencies[word] += 1

This is a mini loop : VALUE named 'frequencies' of its KEY named 'word' (which is also an ARRAY) is instaled to be equal to 1 and each one time more as code run and finds the same key it adds 1 to the value (1+1...). We need to loop the value of exact key, not only the key on its own.


@lgrapstein, maybe here you could find some more explanation:


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