memory and storing references to data structures

S

sdv

I want to hold data from structures in another array, modify the external
structures so that the array still refelects the changes: I've done as
shown underneath but am i storing a 'reference' in the c/c++sense or am I
duplicating data in the 'stuff' object? I dont wont to excessive memory
usage.

def main
stuff=Hash::new()
a1=['a','b','c']
b1=['a','d','f']
ll=nil

['a','b','c','d','e','f'].each {|i|
stuff=Array::new()
}

stuff['a'].push(a1)
stuff['a'].push(b1)
puts "#{stuff['a']}"
a1[0]='foo'
puts "#{stuff['a']}"
end

main
 
J

Joel VanderWerf

sdv said:
I want to hold data from structures in another array, modify the external
structures so that the array still refelects the changes: I've done as
shown underneath but am i storing a 'reference' in the c/c++sense or am I
duplicating data in the 'stuff' object? I dont wont to excessive memory
usage.

def main
stuff=Hash::new()
a1=['a','b','c']
b1=['a','d','f']
ll=nil

['a','b','c','d','e','f'].each {|i|
stuff=Array::new()
}

stuff['a'].push(a1)
stuff['a'].push(b1)
puts "#{stuff['a']}"
a1[0]='foo'
puts "#{stuff['a']}"
end


stuff['a'][0] << "added to stuff['a'][0]"

p a1 # ==> ["foo", "b", "c", "added to stuff['a'][0]"]

So I think you would call it a reference. Does that help?
 
D

daz

sdv said:
I want to hold data from structures in another array, modify the external
structures so that the array still refelects the changes: I've done as
shown underneath but am i storing a 'reference' in the c/c++sense or am I
duplicating data in the 'stuff' object? I dont wont to excessive memory
usage.

def main
stuff=Hash::new()
a1=['a','b','c']
b1=['a','d','f']
ll=nil

['a','b','c','d','e','f'].each {|i|
stuff=Array::new()
}

stuff['a'].push(a1)
stuff['a'].push(b1)
puts "#{stuff['a']}"
a1[0]='foo'
puts "#{stuff['a']}"
end

main



stuff=Hash[]

a1=['a','b','c']
b1=['a','d','f']

['a','b','c','d','e','f'].each {|i|
stuff=Array::new()
}

stuff['a'].push(a1)
stuff['a'].push(b1)
p stuff['a']
a1[0]='foo'
p stuff['a']

a1.size.times do |ix|
p [ a1[ix], stuff['a'][0][ix] ]
puts 'OK' if a1[ix].object_id == stuff['a'][0][ix].object_id
end


#-> [["a", "b", "c"], ["a", "d", "f"]]
#-> [["foo", "b", "c"], ["a", "d", "f"]]
#-> ["foo", "foo"]
#-> OK
#-> ["b", "b"]
#-> OK
#-> ["c", "c"]
#-> OK


Comparing object_id shows whether or not you're referring to
the same objects.
In your example, you are.


daz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top