Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash of Arrays in Ruby

Tags:

arrays

ruby

hash

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?

like image 661
user2823083 Avatar asked Sep 27 '13 18:09

user2823083


1 Answers

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 
like image 61
Cary Swoveland Avatar answered Oct 20 '22 17:10

Cary Swoveland