I am trying to understand this, so let me know how I do. I know
this is probably a breeze for you veterans, but I need to put this in
words. heh
I have a C++/Perl background, so I do understand “associative arrays”,
but understanding Ruby hash objects, and the methods and operations that
can be used with them is pretty new to me.
In the “Ruby Koans” file, “about_hashes.rb”, I completed this method.
It was just a little tough to understand, initially, but I think I got
it. Here’s the test method with helpful line numbers:
def test_default_value_is_the_same_object
-
hash = Hash.new([])
-
hash[:one] << “uno”
-
hash[:two] << “dos”
-
assert_equal [“uno”, “dos”], hash[:one]
-
assert_equal [“uno”, “dos”], hash[:two]
-
assert_equal [“uno”, “dos”], hash[:three]
-
assert_equal true, hash[:one].object_id == hash[:two].object_id
end
Here is my breakdown:
-
a new hash is created, utilizing an empty array as the default value
for any key created without a value, and assigned to “hash”. This
wasn’t too bad, I just had to look up: Hash.new() -
using indexing, the string, “uno”, is appended to the default key
value for the key, :one, which was initially an empty array and is now
the value [“uno”]. Since the “<<” was used instead of the assignment
operator “=”, it is an append, rather than an assign. For example, if
the statement was "hash[:one] = “uno”, then that replaces the default
array and the value is now a String -
same as 2., but what I found interesting was how a new key was used,
and the append still modified the general default value for the entire
hash! So, now the key value default is now: [“uno”, “dos”]
4 - 6 test cases to prove that a default key value was created, with
lines 2 and 3 appending to it, and because these were not assignment
expressions, the keys tested (:one, :two, :three) are using the modified
default value.
- Final proof that is the same default value, or same Array object_id,
being used for the two utilized keys.
So, when you create a Hash object, you can provide a default value. In
this case, the default value is an Array object. Because of this being
an Array object, the “<<” method can be used to modify the default
value. Using indexing on the Hash, this can be tested by querying the
hash:
hash = Hash.new([])
=> {}
hash[:foo]
=> []
hash[:foo] << “hello”
=> [“hello”]
hash[:foo]
=> [“hello”]
hash.inspect
=> {}
The last line “hash.inspect” is what I also find interesting, because if
there are default values, why is it still empty? I then assign a value,
overriding the default value:
hash[:foo] = “bar”
=> “bar”
hash.inspect
=> “{:foo=>“bar”}”
Now, inspect no longer shows an empty hash. Hmmm…
Ruby hashes are an interesting topic and I look forward to your veteran
insight on this topic.
Thanks!