Can I ask a question on Create a Histogram lesson 5


Question why do I need to use [] instead of using ( ) to close the x ?

------ my code ------

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

words = text.split (" ")

frequencies = (0)

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

----- INSTRUCTIONS -------

Use .each to iterate over the words array.
For each word we find, assume that the word itself is a key in frequencies and increment its value by 1.
This is why our default is 0. The first time we find the word, it will have a default value of 0 that we can increment up to 1.

Take a look at the Hint if you need help.

The action we want is to update the hash with a key equal to the word, then increment its value by 1. Each key will be frequencies[word], and we can increment using += 1.


@codecodeuser ,

Are you referring to this line? ...

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

If so, the reason why you need to enclose x in square brackets is that it is being used as a key to access the Hash that has been assigned to frequencies. The reason for not using (), instead, is that you are not making a function call.'

By the way, Codecademy's hint seems to be encouraging you to use the name, word, instead of x. In that case, the line would be ...

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

Though the name of the variable is different, that would be equivalent to what you have.


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