もう少しましになるように書き直し。
class CLP
def initialize(keys={})
@keys = keys
@opts = {}
@args =
enddef hook(key, len=0)
@keys[key] = len;
enddef 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
enddef [](nth)
return @args[nth]
enddef 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"