Regular expressions, strange result from .scan method

J

John Doe

Hi,

I'm having some strange result from the .scan method used on a string.

Here's my code :

a = "counter-46382764"
r = /counter-(\d+)/

puts (a.scan(r)).inspect

It prints : [ [ "46382764" ] ]

I was expecting : [ "46382764" ]
(just a simple array not an array in an array)

What's wrong with me ? :/

Thanks a lot !

pollop.
 
R

Ryan Davis

I'm having some strange result from the .scan method used on a string.
=20
Here's my code :
=20
a =3D "counter-46382764"
r =3D /counter-(\d+)/
=20
puts (a.scan(r)).inspect
=20
It prints : [ [ "46382764" ] ]
=20
I was expecting : [ "46382764" ]
(just a simple array not an array in an array)
=20
What's wrong with me ? :/

Besides not reading the documentation, probably nothing. :p

% irb
"counter-46382764".scan(/counter-(\d+)/) =3D> [["46382764"]]
"counter-46382764".scan(/counter-\d+/) =3D> ["counter-46382764"]
"counter-46382764".scan(/\d+/) =3D> ["46382764"]
ri "String.scan"
=3D String.scan

(from ruby core)
=
--------------------------------------------------------------------------=
----
str.scan(pattern) =3D> array
str.scan(pattern) {|match, ...| block } =3D> str

=
--------------------------------------------------------------------------=
----

Both forms iterate through str, matching the pattern (which may be a
Regexp or a String). For each match, a result is generated and either =
added to
the result array or passed to the block. If the pattern contains no =
groups,
each individual result consists of the matched string, $&. If the =
pattern
contains groups, each individual result is itself an array containing =
one
entry per group.
=20
a =3D "cruel world"
a.scan(/\w+/) #=3D> ["cruel", "world"]
a.scan(/.../) #=3D> ["cru", "el ", "wor"]
a.scan(/(...)/) #=3D> [["cru"], ["el "], ["wor"]]
a.scan(/(..)(..)/) #=3D> [["cr", "ue"], ["l ", "wo"]]
=20

And the block form:
=20
a.scan(/\w+/) {|w| print "<<#{w}>> " }
print "\n"
a.scan(/(.)(.)/) {|x,y| print y, x }
print "\n"
=20

produces:
=20
<<cruel>> <<world>>
rceu lowlr
 

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,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top