Reputation: 42029
I'm reading a book Crafting Rails Applications by Jose Valim and have come across something that I don't understand. I'm wondering if someone can explain the difference in plain English between the three types of hash below.
For example, in what way is the nested hash (as its represented in this example) a nested hash. In other contexts, I understand nested hashes, but don't get it here.
In what way is an "array" a "key" in the second example. To me it looks just like an array with four variables.
In what way is the third example a hash with "hash as key".
@cached[key][prefix][name][partial]
@cached[[key, prefix, name, partial]]
@cached[:key => key, :prefix => prefix, :name => name, :partial => partial]
Upvotes: 1
Views: 567
Reputation: 87506
A hash simply associates key objects to value objects. The keys and values can be anything.
If a value object is itself a hash, you could call it a "nested hash" because in some sense it is inside the main hash.
If a key object is an array, then you get a "hash with array as key".
If a key object is itself a hash, then you get a "hash with hash as key".
See amfeng's answer for a good visual representation of these different cases.
You will need to be somewhat familiar with Ruby syntax to identify the different cases when you see them.
For example, to understand @cached[[key, prefix, name, partial]]
you need to know that [key, prefix, name, partial]
represents an array, so what you have is like @cached[array]
, which means an array is being used as a key.
When you see something like @cached[key][prefix]
you should know that it is equivalent to (@cached[key])[prefix]
so the value object (@cached[key]
) is some sort of object that responds to the []
method. In this case, it is a nested hash because the author told you so, but if you didn't know that context then it is possible for it to be something else.
When you see something like @cached[:key => key, :prefix => prefix, :name => name, :partial => partial]
you should know it equivalent to @cached[{:key => key, :prefix => prefix, :name => name, :partial => partial}]
, which means we are using as hash as a key.
Upvotes: 2
Reputation: 1073
The nested hash, is well, a nested hash. The example given, @cached[key][prefix][name][partial]
, is showing you the "path" to a particular value, so in this case the hash might look something like this:
@cache = {
key => {
prefix => {
name => {
partial => "value"
}
}
}
}
For the simple hash with an array as a key, they're using that 4-element array as one of the keys in the hash.
@cache = {
[key, prefix, name, partial] => "value",
another_key => "another value"
}
For the simple hash with hash as a key, they're using that hash (note that the {}'s for the hash are optional, which may cause some confusion) as one of the keys in the hash.
@cache = {
{:key => key, :prefix => prefix, :name => name, :partial => partial} => "value",
another_key => "another value"
}
Hope that helps!
Upvotes: 6