Regex capture and assign... in one line?

Question, I’ve been using Ruby for a while now and I have a perlism I
kind of miss.

Given

$str = “foo123”;

my ($foo,$bar) = $str =~ /(\w+)(\d+)/;

now we have

$foo; #=> “foo”
$bar; #=> “123”

I know that I can do this in Ruby in TWO lines, but I want to do it in
ONE line. Anyone have any ideas?

On 10/31/06, Nate M. [email protected] wrote:

$foo; #=> “foo”
$bar; #=> “123”

I know that I can do this in Ruby in TWO lines, but I want to do it in
ONE line. Anyone have any ideas?

Something like:

foo, bar = “foo123”.match(/(\w+)(\d+)/).captures

p foo
p bar

pth

On Tuesday October 31 2006 18:56, Patrick H. <“Patrick H.”
[email protected]> wrote:

now we have

Something like:

foo, bar = “foo123”.match(/(\w+)(\d+)/).captures

Better: foo, bar = “foo123”.match(/(\D+)(\d+)/).captures

Hi –

On Wed, 1 Nov 2006, Luiz Eduardo Roncato Cordeiro wrote:

Something like:

foo, bar = “foo123”.match(/(\w+)(\d+)/).captures

Better: foo, bar = “foo123”.match(/(\D+)(\d+)/).captures

The problem with using captures in a single line like this is that if
there’s no match, you’ll get an exception (NoMethodError for
nil#captures). The to_a technique, though it involves discarding the
first value, avoids this problem.

David

Hello,

I know that I can do this in Ruby in TWO lines, but I want to do it in
ONE line. Anyone have any ideas?

m, foo, bar = *“foo123”.match(/(\D+)(\d+)/)

Regards,
Andy S.

Nate M. wrote:

$foo; #=> “foo”
$bar; #=> “123”

I know that I can do this in Ruby in TWO lines, but I want to do it in
ONE line. Anyone have any ideas?

str = “foo123”

foo, bar = str.split( /^(\D*)/ )[1…-1]

foo, bar = str.scan( /\D+|\d+/ )

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs