well, basically I just need a Hash to use String as indexes like
sourceInfo = Hash.new
sourceInfo["var1"]=123
sourceInfo["var2"]=2
sourceInfo["var3"]=3
sourceInfo["var4"]=23
What do you want to happen if sourceInfo["var2"] is assigned a second
time? Do you want to replace it where it originally was in the sequence,
or do you want to delete it and add the new value to the end? Or do you
want both elements to appear at the same time? Or doesn't it matter?
I am just wondering because perhaps all you need is
sourceInfo = []
sourceInfo << ["var1",123]
sourceInfo << ["var2",2]
sourceInfo << ["var3",3]
sourceInfo << ["var4",4]
sourceInfo.each { |k,v| puts "#{k}=>#{v}" }
At least, that's fine if all you want to do is iterate over the
collection and add new elements. Finding or deleting elements by key
requires a linear search:
dummy,value = sourceInfo.find { |k,v| k == "var2" }
However you can optimise this by building a hash as you go which points
to the same elements; or you could build an array containing just the
keys.
class HashAndArray
def initialize
@h, @a = {}, []
end
def [](k)
@h[k]
end
def []=(k,v)
@a << k unless @h.has_key?(k)
@h[k] = v
end
def each
@a.each { |k| yield k,@h[k] }
end
end
sourceInfo = HashAndArray.new
sourceInfo["var1"]=123
sourceInfo["var2"]=2
sourceInfo["var3"]=3
sourceInfo["var4"]=23
sourceInfo.each { |k,v| puts "#{k}=>#{v}" }
puts sourceInfo["var2"]
Adding a delete() method is left as an exercise.