global array of hashes

M

Mario Ruiz

I'm doing this:

$globvar=Array.new()
$globvar[0]="mygenericvalue"
localvar=$globvar
localvar[0]="mylocalvalue"
puts $globvar

And the result for $globvar is "mylocalvalue"

How can I assign to localvar only the value of $globvar and not the
memory possition??

Thanks
 
T

Todd Benson

I'm doing this:

$globvar=Array.new()
$globvar[0]="mygenericvalue"
localvar=$globvar
localvar[0]="mylocalvalue"
puts $globvar

And the result for $globvar is "mylocalvalue"

How can I assign to localvar only the value of $globvar and not the
memory possition??

Thanks

This seems to work...

localvar = $globvar.dup

Todd
 
M

Mario Ruiz

But not in this case:

$globvar=Array.new()
myHash=Hash.new()
myHash["oneValue"]="mygenericvalue"
$globvar[0]=myHash

localvar=$globvar.dup

localvar[0]["oneValue"]="mylocalvalue"

puts $globvar
 
D

David A. Black

Hi --

But not in this case:

$globvar=Array.new()
myHash=Hash.new()
myHash["oneValue"]="mygenericvalue"
$globvar[0]=myHash

localvar=$globvar.dup

localvar[0]["oneValue"]="mylocalvalue"

puts $globvar

Try this:

irb(main):001:0> a = []
=> []
irb(main):002:0> h = {}
=> {}
irb(main):003:0> h["one"] = "generic"
=> "generic"
irb(main):004:0> a[0] = h
=> {"one"=>"generic"}
irb(main):005:0> l = Marshal.load(Marshal.dump(a))
=> [{"one"=>"generic"}]
irb(main):006:0> l[0]["one"] = "local"
=> "local"
irb(main):007:0> a
=> [{"one"=>"generic"}]

(using globals if you absolutely must... but that's another story :)


David

--
Rails training from David A. Black and Ruby Power and Light:
ADVANCING WITH RAILS April 14-17 New York City
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
See http://www.rubypal.com for details and updates!
 
T

Todd Benson

But not in this case:

$globvar=Array.new()
myHash=Hash.new()
myHash["oneValue"]="mygenericvalue"
$globvar[0]=myHash

localvar=$globvar.dup

localvar[0]["oneValue"]="mylocalvalue"

puts $globvar

In this case, you create a new array that holds the same Hash object.
You have to dup the Hash as well.

hth,
Todd
 

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
474,289
Messages
2,571,450
Members
48,127
Latest member
svastipharmancrr

Latest Threads

Top