実装
require "strscan"
def parse_ini src
section = { "" => {} }
current = section[""]
s = StringScanner.new(src)
while !s.eos?
case
when s.scan(/\s+/)
# nothing
when s.scan(/\[(.+?)\]/)
section[s[1]] = current = {}
when s.scan(/(\w+)\s*=\s*(["'])?([^\n]+)\2/)
current[s[1]] = s[3]
when s.scan(/(\w+)\s*=\s*(\d+\.\d+)/)
current[s[1]] = s[2].to_f
when s.scan(/(\w+)\s*=\s*([\d]+)/)
current[s[1]] = s[2].to_i
else
raise "Parse Error. rest=#{ s.rest }"
end
end
return section
end
if $0 == __FILE__
require "pp"
pp parse_ini(DATA.read)
end
__END__
piyo = "piyopiyo"
[foo]
name = "hoge"
age = 20
point = 10.7
[bar]
hoge = 'hogehoge'
実行結果
% ruby /tmp/aaa.rb
{""=>{"piyo"=>"piyopiyo"},
"foo"=>{"name"=>"hoge", "age"=>20, "point"=>10.7},
"bar"=>{"hoge"=>"hogehoge"}}
感想
Rubyでテキストをパースする時はstrscanが本当に便利!
もう正規表現には戻れない。