Block form of 'scan' with one set of parens

M

Matthew Westcott

Hi,
Newbieish syntax question - I'm using the block form of 'scan' like this:

"<foo,bar> <foo,baz> <foo,blarg>".scan(/<(\w*),(\w*)>/) { |first,second|
puts "#{first.upcase} and #{second.upcase}\n"
}

which works fine. However, if the regex only has one set of parentheses,
I can't do

"<bar> <baz> <blarg>".scan(/<(\w*)>/) { |first|
puts "#{first.upcase}\n"
}

because it assumes that I want 'first' to be an array of all the matched
groups, and so it dies with
"undefined method `upcase' for ["bar"]:Array (NameError)".

Is there any way to persuade Ruby to treat |first| as a (singleton) list
of strings to be assigned? I can use |first,dummy| as a workaround, but
is there a neater way that I'm missing?

Thanks,
- Matthew
 
R

Robert Klemme

Matthew Westcott said:
Hi,
Newbieish syntax question - I'm using the block form of 'scan' like this:

"<foo,bar> <foo,baz> <foo,blarg>".scan(/<(\w*),(\w*)>/) { |first,second|
puts "#{first.upcase} and #{second.upcase}\n"
}

which works fine. However, if the regex only has one set of parentheses,
I can't do

"<bar> <baz> <blarg>".scan(/<(\w*)>/) { |first|
puts "#{first.upcase}\n"
}

because it assumes that I want 'first' to be an array of all the matched
groups, and so it dies with
"undefined method `upcase' for ["bar"]:Array (NameError)".

Is there any way to persuade Ruby to treat |first| as a (singleton) list
of strings to be assigned? I can use |first,dummy| as a workaround, but
is there a neater way that I'm missing?

Try this:

"<bar> <baz> <blarg>".scan(/<(\w*)>/) { |first,|
puts "#{first.upcase}"
}

Note: putting a "\n" at the end of a string that is printed with puts does
not have any effect, you'll have to put two "\n" if you want to have an
additional line.

Kind regards

robert
 

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,780
Messages
2,569,614
Members
45,289
Latest member
stfp04

Latest Threads

Top