regex capture and assign... in one line?

N

Nate Murray

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

Patrick Hurley

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
 
D

dblack

Hi --

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

--
David A. Black | (e-mail address removed)
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
 
A

Andrew Stewart

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
 
W

William James

Nate said:
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+/ )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top