# Troubles with nested hashes

**URL:** <https://www.ruby-forum.com/t/troubles-with-nested-hashes/188081>\
**Category:** Ruby\
**Created:** [May 5, 2010, 1:40pm UTC](https://www.ruby-forum.com/t/troubles-with-nested-hashes/188081 "2010-05-05T13:40:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![teedubb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/d6d6ee/32.png) [@teedubb](https://www.ruby-forum.com/u/teedubb)\
**Post date:** [May 5, 2010, 1:40pm UTC](https://www.ruby-forum.com/t/troubles-with-nested-hashes/188081/1 "2010-05-05T13:40:14Z")

</div>

i’m new to ruby and not that great a programmer so bear with me. i’m  
trying to dynamically populate a nested hash. below is the structure of  
what i’m trying to populate

devices = {  
‘macaddr’ =\> {  
‘packets’ =\> ‘’,  
‘ip’ =\> ‘’,  
‘name’ =\>  
}  
}

macaddr is my unique identifier and it will have certain properties  
(packets, ip, and name). just so you know i’m reading the information  
over the network, which is simply a comma separated line of text, and  
putting that into an array like below.

Csv.parse(whatever) do |line|  
devices[‘macaddr’] = line[0]  
devices[‘macaddr’][‘packets’] = line[1]  
end

it fails here =\> devices[‘macaddr’][‘packets’] = line[1]

i also tried another approach, instead of defining the nested hash i  
used the code below.

devices = Hash.new{|h,k| h[k]=Hash.new(&h.default.proc)}  
Csv.parse(whatever) do |line|  
devices[‘macaddr’] = line[0]  
devices[‘macaddr’][‘packets’] = line[1]  
end

it still fails on the same line, any clue on what i’m doing wrong? also  
is this the best approach? thanks.

---

<div class="post-metadata">

**Author:** ![teedubb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/d6d6ee/32.png) [@teedubb](https://www.ruby-forum.com/u/teedubb)\
**Post date:** [May 5, 2010, 2:06pm UTC](https://www.ruby-forum.com/t/troubles-with-nested-hashes/188081/2 "2010-05-05T14:06:44Z")

</div>

When you do this

devices[‘macaddr’] = line[0]

You are saying that the hash ‘devices’ has the key ‘macaddr’ and that  
contains the value that is held in ‘line[0]’. Then you say

devices[‘macaddr’][‘packets’] = line[1]

This says that hash ‘devices’ has a key ‘macaddr’ which is a hash!

For this to work, as written, the line[0] needs to be a hash. I suspect  
that  
it is not. What you probably want is this

Csv.parse(whatever) do |line|  
macaddr = line[0]

# Notice there are no quotes

devices[macaddr] = {  
‘packets’ =\> line[1],  
‘ip’ =\> line[2],  
… etc  
}  
end

---

<div class="post-metadata">

**Author:** ![teedubb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/d6d6ee/32.png) [@teedubb](https://www.ruby-forum.com/u/teedubb)\
**Post date:** [May 5, 2010, 3:37pm UTC](https://www.ruby-forum.com/t/troubles-with-nested-hashes/188081/3 "2010-05-05T15:37:18Z")

</div>

thanks Peter, that solved my issue.
