I came across an old piece of code which was creating the hash datatype using simple arrays in ruby. I get most of it, except one part:
The point as I understand it is, every element of @store
is a memory location for a particular key/value pair, as a function of the key. So @store[3]
would generally store key/value pairs corresponding to key=3, key=53, ... and in general where key % size == 3
(in this case size = 50).
However, when I set hash[3] = 7
, hash[53] = 9
, etc., every element of @store
array is populated with the key/value pairs, and not just the index 3 element. It seems like the line @store[store_key] << [key, value]
in the method []=(key, value)
is adding [key, value] to every element of @store
, and not just one with the index store_key
. Any ideas?
class SimpleHash
attr_accessor :size, :store
def initialize(size)
@size = size
@store = Array.new(size, [])
end
def []=(key, value)
store_key = key % @size
index = find_key(key, @store[store_key])
if index
@store[store_key][index][1] = value
else
p "***********************************"
p @store
@store[store_key] << [key, value]
p "after"
p store_key
p @store
end
end
end
hash = SimpleHash.new(50)
p hash
hash[3] = 5
p hash
hash[3] = 7
hash[53] = 9
hash[103] = 11
hash[104] = 11
Although your question's a bit unclear, I can guess what the problem is.
@store = Array.new(size, [])
That creates an array of the right size, but where every element is the SAME OBJECT.
Change the array-within-an-array at any position, and the change will be evident in every position.
Try instead
@store = Array.new
size.times { @store << [] }
Every sub-array will be a separate object that way.
EDIT
@nafaa boutefer's answer is better. The block gets evaluated for each instance of the array so each sub-array is a different object.
@store = Array.new(size){ [] }
You can simply do this
@store = Array.new(size){ [] }
Every element is a separate array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.