Why does printing out frequencies work?


#1

I am surprised that default solution is working.

frequencies.each do |word, frequency|
puts word + " " + frequency
end

Frequencies is array of arrays, something like this:

frequencies = [["Sally", 3], ["Harry", 2], ["met", 1]]

I would expect that each will give you an array, not 2 values. I would expect that you need to write it like this:

frequencies.each do |frequency|
puts frequency[0] + " " + frequency[1]
end

What's going on behind the scenes to make first example work?


#2

It's simpler to see a hash as a collection of keys and values rather than as an array of arrays, because you use it when you don't want to use arrays most of the time (because you need your own keys instead of simply integers).

Now, as for why the solution you mention works, it's just that instead of using only the value in an array, the each method will use both the key and the value when you pass a hash to it, and it knows it must use the first variable as a substitute for the key, and the second variable as a substitute for the value.

Your proposed solution will also work, but as I said, your goal when you use a hash is not to deal with an array of arrays, but rather a collection of items with a "label" and a "content", that's why it's preferable to use the default solution.


#3

Sorry, I still don't understand it.
And I have an additional question:
When we created frequencies, we created it as a hash.
Then we populate it with strings as keys, and integers as values.
Then, we call frequencies.sort.
What I don't understand is how can you use .sort, which is a method of the Array class, on frequencies, which is a Hash.
And I still don't get the original question, because the .sort method gives back an array of arrays, not a hash, and yet, in the .each method, referencing each "sub-array" as a key-value pair, works. Why?


#4

Different objects can answer to the same methods. I don't know if inside Ruby it's exactly the same method or a variant also called sort, but it's perfectly possible for two different objects to respond to the exact same method if you need to (you'll see that later in the course on objects and classes).

Probably because each behaves differently when it receives one substitute and when it receives two. When it receives one (I tested it), it considers it an Array object (whether it's called on a hash or an array by the way). When it receives two substitutes, it considers them as the type of the data contained in each element (in our example, String and Integer respectively).

It's hard to know for sure how each works in details unless we have the code to be honest. But it's interesting, I'd be glad if someone with more knowledge on the language could share his insights.