Regular expressions, strange result from .scan method

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®).inspect

It prints : [ [ “46382764” ] ]

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

What’s wrong with me ? :confused:

Thanks a lot !

pollop.

On Feb 21, 2011, at 13:10 , John D. wrote:

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

What’s wrong with me ? :confused:

Besides not reading the documentation, probably nothing. :stuck_out_tongue:

% irb

“counter-46382764”.scan(/counter-(\d+)/)
=> [[“46382764”]]

“counter-46382764”.scan(/counter-\d+/)
=> [“counter-46382764”]

“counter-46382764”.scan(/\d+/)
=> [“46382764”]

ri “String.scan”
= String.scan

(from ruby core)

str.scan(pattern) => array
str.scan(pattern) {|match, …| block } => 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.

   a = "cruel world"
   a.scan(/\w+/)        #=> ["cruel", "world"]
   a.scan(/.../)        #=> ["cru", "el ", "wor"]
   a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
   a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

And the block form:

   a.scan(/\w+/) {|w| print "<<#{w}>> " }
   print "\n"
   a.scan(/(.)(.)/) {|x,y| print y, x }
   print "\n"

produces:

   <<cruel>> <<world>>
   rceu lowlr