Variable assignment


In the last project, we call sort_by on a hash which returns an array of arrays, but ruby has no problem with us assigning this to a hash. Is there a reason this works?


I already discussed this with someone else on this forum, and my theory is that hashes are different objects from arrays but still behave as arrays of arrays. And as soon as you sort_by a hash, it seems to become of the type Array rather than the type Hash, but it's separated from the variable (which can contain any type of object), so it doesn't cause any problem.

I don't have enough knowledge in the language to know exactly how it works though.


A hash is an associative array. If we examine frequencies before sorting, this is what we have:

{"the"=>2, "rain"=>1, "in"=>2, "Spain"=>1, "falls"=>1, "mainly"=>1, "plains"=>1}

An associative array cannot be sorted since it has no order to begin with. But it can be mapped to an array that can be sorted. The result is an array so that it maintains its sorted order and has a numerical index.

[["the", 2], ["in", 2], ["Spain", 1], ["falls", 1], ["mainly", 1], ["rain", 1], ["plains", 1]]


Ah, that makes sense. Thanks for the response!


Thanks @mtf for the clarification, so I assume the Hash class inherits from the Array class?

Also, do you know if there are methods which can only be used on hashes and not on arrays?