Troubles with nested hashes

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.

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

thanks Peter, that solved my issue.