[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

regex capture and assign... in one line?

Nate Murray

10/31/2006 9:50:00 PM

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?

5 Answers

Patrick Hurley

10/31/2006 9:57:00 PM

0

On 10/31/06, Nate Murray <jashmenn@gmail.com> wrote:
> 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?
>
>
>


Something like:

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

p foo
p bar

pth

Luiz Eduardo Roncato Cordeiro

10/31/2006 10:13:00 PM

0

On Tuesday October 31 2006 18:56, Patrick Hurley <"Patrick Hurley" <phurley@gmail.com>> wrote:
> On 10/31/06, Nate Murray <jashmenn@gmail.com> wrote:
> > 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?
> >
> >
> >
>
>
> Something like:
>
> foo, bar = "foo123".match(/(\w+)(\d+)/).captures

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

>
> p foo
> p bar
>
> pth
>
>

dblack

10/31/2006 10:50:00 PM

0

Andrew Stewart

11/1/2006 12:36:00 PM

0

Hello,

> 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?

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

Regards,
Andy Stewart



William James

11/1/2006 10:55:00 PM

0


Nate Murray wrote:
> 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?

str = "foo123"

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

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