# File.open.each() while using a 2 level hash

**URL:** <https://www.ruby-forum.com/t/file-open-each-while-using-a-2-level-hash/143777>\
**Category:** Rails\
**Created:** [July 22, 2008, 5:51pm UTC](https://www.ruby-forum.com/t/file-open-each-while-using-a-2-level-hash/143777 "2008-07-22T17:51:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 22, 2008, 5:51pm UTC](https://www.ruby-forum.com/t/file-open-each-while-using-a-2-level-hash/143777/1 "2008-07-22T17:51:24Z")

</div>

I am doing:  
SourceHash = {}  
File.open(“file\_to\_open”).each {|line|  
SourceHash[var[3]] = {}  
puts SourceHash[‘VALUE’][‘cktid’]  
}

var is just an array of each csv value.

The error says undefined method [] for nil:NilClass in ‘each’

If I take the hash statement out of the file loop it works. Any ideas  
why the “each” method is throwing an error while trying to get a value  
out of a 2 level hash??

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 22, 2008, 6:58pm UTC](https://www.ruby-forum.com/t/file-open-each-while-using-a-2-level-hash/143777/2 "2008-07-22T18:58:19Z")

</div>

Unless var[3] == ‘VALUE’ then SourceHash[‘VALUE’] is going to return a  
nil, and your puts expression amounts to nil[‘cktid’], which would  
produce the error you describe.

Also–in ruby, variables that begin w/capital letters are constants–you  
should rename to source\_hash or something in order to decrease your risk  
of confusing the interpreter.

HTH,

-Roy
