Setting a hash equals another hash in Ruby

I want to track the counts of some elements with an arbitrary name, and then reset the numbers to zero. My thought was this:

reset_hash={"string1"=>0,"string2"=>0,"string3"=>0}
=> {"string1"=>0, "string2"=>0, "string3"=>0} 

new_hash = reset_hash
=> {"string1"=>0, "string2"=>0, "string3"=>0} 

new_hash["string1"]=1
new_hash["string3"]=1
new_hash
=> {"string1"=>1, "string2"=>0, "string3"=>1}

...

Now I want to reset new_hash back to reset_hash:

new_hash = reset_hash
=> {"string1"=>1, "string2"=>0, "string3"=>1}
reset_hash
=> {"string1"=>1, "string2"=>0, "string3"=>1} 

What's going on here? It seems that reset_hash really was set to new_hash, which is the opposite of what I wanted. How to implement the desired behavior?

+5
source share
4 answers

If you have a variable pointing to an object, you really have a reference to the object. If both a and b point to a hash {1 => 3, "foo" => 54}, changing a or b will change the other.

However, you can use a combination of the two methods to do what you want.

:

new_hash = Hash.new(0)

0:

new_hash["eggs"]  # -> 0

:

new_hash["string1"] += 1 # => 1

,

new_hash.clear # => {}

reset, 0.

, , , - .

irb(main):031:0> b = Hash.new("Foo") #=> {}
irb(main):032:0> b[3] #=> "Foo"
irb(main):033:0> b[33] #=> "Foo"
irb(main):034:0> b[33].upcase! #=> "FOO"
irb(main):035:0> b[3] # => "FOO"

, -:

h = Hash.new {|hash, key| hash[key] = "new default value"}

, :

d = Hash.new{ |hash,key| hash[key] = "string"} #=> {}
d[3] # => "string"
d[3].upcase! #=> "STRING"
d[5] #=> "string"
+5

, clone. :

reset_hash={"string1"=>0,"string2"=>0,"string3"=>0}
new_hash = reset_hash.clone

new_hash["string1"]=1
new_hash["string3"]=1
new_hash

new_hash = reset_hash.clone
reset_hash
+5

.

. , &ndash, -instdance.

Perhaps you want to copy the hash first? If you do this and you have a hash with complex objects, you will also need to investigate shallow and deep copies / cloning.

+2
source

You need to use the clone to create your copy.

See fooobar.com/questions/38618 / ...

Otherwise, you only create 2 "pointers" for the same hash, and not for copying the contents.

Then use replace to copy the cloned content back to the existing hash.

+1
source

All Articles