適当なコマンドラインパーサ その2

もう少しましになるように書き直し。


class CLP
def initialize(keys={})
@keys = keys
@opts = {}
@args =
end

def hook(key, len=0)
@keys[key] = len;
end

def parse(args)
while prm = args.shift
if (prm =~ %r|^[-/]|) && @keys.has_key?($')
key = $'
buf =
@keys[key].times {
break if args.empty? || args.first =~ %r|^[-/]|
buf << args.shift
}
if @keys[key] < 2
@opts[key] = buf.empty? ? "" : buf.first
else
@opts[key] = buf
end
else
@args << prm
end
end
end

def [](nth)
return @args[nth]
end

def method_missing(name, *args)
return args.empty? ? @opts[name.to_s] : super
end
end


clp = CLP.new("o1"=>0, "o2"=>1)
p ARGV #=> ["-o1", "-o2", "foo", "bar", "zoo"]
clp.parse(ARGV)
p clp.o1 #=> ""
p clp.o2 #=> "foo"
p clp.o3 #=> nil
p clp[0] #=> "bar"
p clp[1] #=> "zoo"