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


#1



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

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

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


#2
  1. Your idea

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

doesn't convert Fixnum.

2.

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.


#3

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


#4

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