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.
% 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