# Parse file to a hash

**URL:** <https://www.ruby-forum.com/t/parse-file-to-a-hash/188178>\
**Category:** Ruby\
**Created:** [May 6, 2010, 10:36pm UTC](https://www.ruby-forum.com/t/parse-file-to-a-hash/188178 "2010-05-06T22:36:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jpedrosa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/ecae2f/32.png) [@jpedrosa](https://www.ruby-forum.com/u/jpedrosa)\
**Post date:** [May 6, 2010, 10:36pm UTC](https://www.ruby-forum.com/t/parse-file-to-a-hash/188178/1 "2010-05-06T22:36:32Z")

</div>

Hello!

I need to parse a specific file to a hash. This is a sample of the file:

blablabla…  
}  
– 1.3.6.1.4.1.000.6.1.2.2.11.1  
mASLocked OBJECT-TYPE  
SYNTAX INTEGER  
…blablabla

And my hash has to be like this:

my\_hash = {  
‘mASLocked’ =\> ‘1.3.6.1.4.1.000.6.1.2.2.11.1’  
}

The hash will have about 400 items on it.

The only 2 things that are standard on the file are the '-- ’ before the  
number and the string ‘OBJECT-TYPE’ on the second line.

I saw a lot of parse examples but they always use something like DATA  
SEPARATION DATA. This is not my case since the identifier is in one line  
before the data and in the other line after the data I want.

I am thinking of doing something very ugly here. Any ideas to save me  
from do a ugly Frankenstein (and probably wrong) code?

Thanks

---

<div class="post-metadata">

**Author:** ![jpedrosa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/ecae2f/32.png) [@jpedrosa](https://www.ruby-forum.com/u/jpedrosa)\
**Post date:** [May 6, 2010, 11:36pm UTC](https://www.ruby-forum.com/t/parse-file-to-a-hash/188178/2 "2010-05-06T23:36:29Z")

</div>

On Thu, May 6, 2010 at 3:37 PM, Joao P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> 

You might try String#scan with a multiline regex.

text =\<\<EOF  
– 1.3.6.1.4.1.000.6.1.2.2.11.1  
mASLocked OBJECT-TYPE  
SYNTAX INTEGER  
EOF

hash = Hash.new

regex = /-- (.+)\n\s+(.+) OBJECT-TYPE/m

text.scan(regex) do |value,key|  
hash[key] = value  
end

p hash

p hash
