Quoted Argument Parsing in Ruby

May 4th, 2009

I had a post half-written for today, but decided it wasn’t going anywhere interesting and scrapped it. I still wanted to post something, so in the spirit of half-finished things, here’s a nice Ruby one-liner from a half-finished project of mine:

gets.chomp.strip.scan(/[^ "]+|"[^"]+"/).map{ |s| s.delete('"') }

This takes a line from standard input and splits it into a space-delimited argument list, with support for quoted arguments that have spaces in them. If you enter 'command with "some parameters"', you’ll get the array ["command", "with", "some parameters"]. Not particularly advanced, but maybe useful.

No comments yet.