tags:

views:

57

answers:

1

How can I parse strings in ruby like many command line utilities do? I've got strings similar to "command [--opt1=...] [--enable-opt2] --opt3=... arg1" and methods similar to command(opt1,opt2,opt3,arg1...). I want to let arguments to come in random order, some of them can be optional.

At the moment I wrilte regexp every time I need to parse new command, as for example to parse "lastpost --chan=your_CHANNEL /section/"

I have this regular expression:

    text = "lastpost --chan=0chan.ru /s/"
    command = (text.match /^\w+/)[0]
    args = text.gsub(/^\w+/,'')
    if args =~ /[[:blank:]]*(--chan\=([[:graph:]]+)[[:blank:]]+)*\/?(\w+)\/?/
        chan = $2
        section = $3
        do_command(chan,section)
    else
        puts "wrong args"
    end

I wish i had create_regexp(opts,args), which should produce regular expression.

+1  A: 

Ok, I found optparse can do it for me

If you have (sub)commands, check out the `commander` gem.
Marc-André Lafortune