On 30.01.2007 21:25, El Gato wrote:
> I find myself doing something like this a lot lately:
> 
> # where result is most often the textual output of a %x{command}
> (c = result.match(/id: (\d+)/)) ? c.captures.first : result.scan(/error:
> (.*)/).to_s
> 
> Is there a smoother/better way to say this?

Yes.  Use String#[]:

your_match = result[/id: (\d+)/, 1] || result[/error: (.*)/, 1]

Note: your second part "result.scan" will always return at most one 
match because of ".*".  That's the reason why a single match like mine 
yields the same output.

Other alternatives:

This one is more interesting if you extract different portions of the match:

your_match = case result
   when /id: (\d+)/
     $1
   when /error: (.*)/
     $1
   else
     nil
end

In your case you can have it simpler:

your_result = /id: (\d+)/ =~ result || /error: (.*)/ =~ result ? $1 : nil

But I'd prefer the first variant. :-)

Kind regards

	robert