Hello all,
I would like to store arrays in a hash, indexed by a string key. I
would like to have the hash create an empty array as the default value,
when it sees a new key, something like the code involving “hash1” below.
However, this code is giving some strange results – it claims that the
hash is empty, even though there is an array stored in it, and I can
then retrieve that array.
I am new to ruby, so maybe I am just doing something stupid (… I am
not sure about that “Hash.new( [] )” for example… )
Can anyone explain these results?
Thanks.
CODE:
#!/usr/bin/ruby
hash1 = Hash.new( [] )
hash1[“hello”].push(1.0)
hash1[“hello”].push(2.0)
$stderr.write “hash1.size() = #{hash1.size()}\n”
$stderr.write “hash1.empty() = #{hash1.empty?()}\n”
$stderr.write “hash1[“hello”].size() = #{hash1[“hello”].size()}\n”
$stderr.write “hash1[“hello”] = #{hash1[“hello”]}\n”
hash2 = {“hello” => [1.0,2.0]}
$stderr.write “\nhash2.size() = #{hash2.size()}\n”
$stderr.write “hash2.empty() = #{hash2.empty?()}\n”
$stderr.write “hash2[“hello”].size() = #{hash2[“hello”].size()}\n”
$stderr.write “hash2[“hello”] = #{hash2[“hello”]}\n”
OUTPUT:
hash1.size() = 0
hash1.empty() = true
hash1[“hello”].size() = 2
hash1[“hello”] = 1.02.0
hash2.size() = 1
hash2.empty() = false
hash2[“hello”].size() = 2
hash2[“hello”] = 1.02.0
VERSION:
ruby 1.8.3 (2005-09-21) [i686-linux]