Over a million developers have joined DZone.

Parse Windows .ini Format With Ruby

·
I didn't write this, I'm just posting it in case someone else finds it useful. I needed to parse a file that turned out to be windows .ini. gdsx in #ruby-lang came up with this for me. 


  #thanks to gdsx in #ruby-lang
  def tame(input)
          tamed = {}

          # split data on city names, throwing out surrounding brackets
          input = input.split(/\[([^\]]+)\]/)[1..-1]

          # sort the data into key/value pairs
          input.inject([]) {|tary, field|
                  tary << field
                  if(tary.length == 2)
                          # we have a key and value; put 'em to use
                          tamed[tary[0]] = tary[1].sub(/^\s+/,'').sub(/\s+$/,'')
                          # pass along a fresh temp-array
                          tary.clear
                  end
                  tary
                  }

          tamed.dup.each { |tkey, tval|
                  tvlist = tval.split(/[\r\n]+/)
                  p tvlist
                  tamed[tkey] = tvlist.inject({}) { |hash, val|
                          k, v = val.split(/=/)
                          hash[k]=v
                          hash
                          }
                  }

          tamed
  end

here's what the input looks like

[Amsterdam]  
Address=Amstelveenseweg 438;1084 JH;Amsterdam

[Antwerp]  
Address=Uitbreidingstraat 4;4-600;Antwerp

[Austin]  
Address=4221 South Harbor Expressway, Suite 400;Austin, Texas 78746

[Baltimore / Smith]
City=Baltimore 
Address=225 Johnson Avenue;Baltimore, Maryland 21209-3600

[Baltimore / Calvert]
City=Baltimore
Address=151 South Belmont Street, Suite 2350;Baltimore, Maryland 21202-6832

[Bangkok]
Address=Unit 543, London Tower;495 North Sathorn Road, Yannawa, Sathorn Bangkok 45467
Country=Thailand

[Bergen]
Country=Norway  
City=Bergen
Address=Torgallmenningen 4B;PO Box 2153 Sentrum, N-5811;Bergen



here's the output

{"Bergen"=>{"City"=>"Bergen", "Country"=>"Norway", "Address"=>"Torgallmenningen 4B;PO Box 2153 Sentrum, N-5811;Bergen"}, "Antwerp"=>{"Address"=>"Uitbreidingstraat 4;4-600;Antwerp"}, "Baltimore / Smith"=>{"City"=>"Baltimore", "Address"=>"225 Johnson Avenue;Baltimore, Maryland 21209-3600"}, "Amsterdam"=>{"Address"=>"Amstelveenseweg 438;1084 JH;Amsterdam"}, "Bangkok"=>{"Country"=>"Thailand", "Address"=>"Unit 543, London Tower;495 North Sathorn Road, Yannawa, Sathorn Bangkok 45467"}, "Austin"=>{"Address"=>"4221 South Harbor Expressway, Suite 400;Austin, Texas 78746"}, "Baltimore / Calvert"=>{"City"=>"Baltimore", "Address"=>"151 South Belmont Street, Suite 2350;Baltimore, Maryland 21202-6832"}


Is this also an example of a state machine in Ruby?
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}