Regex loop yields single element array for multiple finds


#1

I have a string with say “@@@asdfasdf@@@ @@@ lk;lk@@@” called markup,
and I do:

markup.scan(/@@@/) do |ats|
print ats.class
print ats.length
end

and I get the class as always Array, and the length as 1. What’s with
that?

xc


#2

On Sat, 29 Apr 2006, Xeno C. wrote:

I have a string with say “@@@asdfasdf@@@ @@@ lk;lk@@@” called markup, and I do:

markup.scan(/@@@/) do |ats|
print ats.class
print ats.length
end

and I get the class as always Array, and the length as 1. What’s with that?

xc

harp:~ > ri String.scan
------------------------------------------------------------ String#scan
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(/(.)(.)/) {|a,b| print b, a }
     print "\n"

  _produces:_

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

-a


#3

On Apr 28, 2006, at 7:26 PM, Xeno C. wrote:

I have a string with say “@@@asdfasdf@@@ @@@ lk;lk@@@” called
markup, and I do:
[…]
and I get the class as always Array, and the length as 1. What’s
with that?

“@@@asdfasdf@@@ @@@ lk;lk@@@”.scan(/@@@/) do |ats|
ats # => “@@@”, “@@@”, “@@@”, “@@@”
ats.class # => String, String, String, String
end

You must be doing something else.

– Daniel


#4

irb(main):090:0* markup = “@@@asdfasdf@@@ @@@ lk;lk@@@”
=> “@@@asdfasdf@@@ @@@ lk;lk@@@”
irb(main):091:0> markup.scan(/@@@/) do |ats|
irb(main):092:1* puts ats.length
irb(main):093:1> end
3
3
3
3
=> “@@@asdfasdf@@@ @@@ lk;lk@@@”
irb(main):094:0>

On Apr 28, 2006, at 10:26 AM, Xeno C. wrote:

xc

– Elliot T.