Rubyの標準ライブラリStringScannerがすごい!

もう5日ですが、あけましておめでとうございます。
毎年新年の目標を立てるのですが、なかなか難しいものですね。けど、今年は頑張ります!

さて、文字列処理に強いプログラミング言語と言えばPerlが有名ですがRubyもすごいんです。Rubyの標準ライブラリ「StringScanner」を使えばパーサをあっという間に書けるんです。

試しにWindowsでよく目にする「.ini」ファイルを読み込みRubyのハッシュに読み込むプログラムを書いてみます。

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'

簡単ですね。
さらに、この「StringScanner」はC言語で実装されているのでとても高速です。標準ライブラリなのでレンタルサーバ等でもそのまま使えお手軽ですね。あ、マニュアルはこちらから。
http://www.ruby-lang.org/ja/man/html/strscan.html

Rubyは本当にいい言語ですね!