简体   繁体   中英

Hash of Arrays in Ruby

I have one hash, where key is a string and value is an array of a string. I want something like this:

{"k1"=>["v1", "v2"], "k2"=>["v3", "v4"]} 

I have only one hash and one array to implement this. I have coded something like this:

hash1 = Hash.new
arr = Array.new
arr.push "v1"
arr.push "v2"
hash1["k1"] = arr 

#hash is like this: {"k1"=>["v1", "v2"]
#Now I clear the array to read the new values

arr. clear
arr.push "v3"
arr.push "v4"
hash1["k2"] = arr
puts hash1

#Output: {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]}
#Notice that k1's value also got updated

Then I changed one line:

hash1 = Hash.new
arr = Array.new
arr.push "v1"
arr.push "v2"
hash1["k1"] = arr 

arr = [] # ** This is the only changed line.  Now k1's value is correct. **
arr.push "v3"
arr.push "v4"
hash1["k2"] = arr
puts hash1
#Output: {"k1"=>["v1", "v2"], "k2"=>["v3", "v4"]} (which I wanted)

Can someone please explain me how does this happen? I am very new to Ruby. Ideally, what is the correct way to code this problem?

This should show you what is happening ( object_id is your friend). (I've inserted an underscore in the Object_id to make it easier to see differences.)

hash1 = {}            # => {} 
arr = ["v1", "v2"]    # => ["v1", "v2"] 
arr.object_id         # => 7016637_4343580 
hash1["k1"] = arr     # => ["v1", "v2"] 
hash1                 # => {"k1"=>["v1", "v2"]}
hash1["k1"].object_id # => 7016637_4343580 
arr.clear             # => [] 
arr.object_id         # => 7016637_4343580 
arr << "v3" << "v4"   # => ["v3", "v4"] 
arr.object_id         # => 7016637_4343580 
hash1["k2"] = arr     # => ["v3", "v4"] 
hash1                 # => {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]} 
hash1["k1"].object_id # => 7016637_4343580 
hash1["k2"].object_id # => 7016637_4166580 

arr = []              # => [] 
arr.object_id         # => 7016637_4036500 
arr = ["v5", "v6"]    # => ["v5", "v6"] 
arr.object_id         # => 7016637_3989880 
hash1                 # => {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]} 
hash1["k1"].object_id # => 7016637_4343580 
hash1["k2"] = arr     # => ["v5", "v6"] 
hash1                 # => {"k1"=>["v3", "v4"], "k2"=>["v5", "v6"]} 
hash1["k1"].object_id # => 7016637_4343580 
hash1["k2"].object_id # => 7016637_3989880 

The array you saved on the hash is still referenced with arr so clearly doing arr.clear and using arr.push would clean up and add new values to the one saved on the hash as well. However doing arr = [] , arr would now reference a new array which is different from the one saved in hash.

And you can simply add a new array to hash with:

hash1["k2"] = ["v3", "v4"]

Or

hash1["k2"] = %w[v3 v4]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM