Stefano said:
I think it's easier (and more efficient) to create a new array with the
current values of i and j at each iteration, instead of modifying one
single
array and duping it.
for i in 1..2
for j in 1..2
h2[[i,j]] = "ha"
end
end
that is already listed in the initial program. the main requirement is
that I have a list (an array), and how do I use it as a hash key.
But this code does meet this requirement.
[i,j] IS an array, so
h2[[i,j]] = "ha"
is storing "ha" in the hash with a key which is an array containing
references to the objects currently referenced by i and j.
I think you might be tripping over the difference between a variable
and an object here. I know that lots of posters to this forum do.
Variables aren't objects per se. A variable references an object.
Variable assignment copies the reference NOT the object.
So, at the risk of being pedantic.
a = [i,j] # a now refers to the object which was generated by the
literal [i,j]
h[a] = "foo" # The hash now has a key which references the same object
a = "Something else" # a now refers to the string, but the hash
still references the array through the key.
h[["betty", "boop"] = "boop, boop, a doo" # h now ALSO references
the object generated by the array literal as a new key.
I would say that best practice for hash keys is to use either literal
values or expressions for keys, OR variables whose scope doesn't last
outside of the code which stores the key,value, you want to control
cases where an object being used as a key in a hash changes outside of
the hash.
You seem to be worried about the memory requirements for storing the
keys. I'm not sure there's much that can be done about that though,
If you want to have a hash with 10,000 entries, then all 10,000 keys
are going to have to be unique and will have to be stored.
When that becomes an issue, you probably want to explore other
implementations which store the key->value mapping externally, say a
database or something in between.