[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Does String#scan(/(..)(..)/) produce an array of arrays?

RLMuller

9/14/2003 8:35:00 AM

Hi All,

"Programming Ruby" says the following for String#scan at http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_string.html#S...:

a = "cruel world"

...

a.scan(/(..)(..)/) » [["cr", "ue"], ["l ", "wo"]]



I wrote the following to test whether scan actually produced an array or arrays:



a = "cruel world"
ar = a.scan(/(..)(..)/)
puts "Type of ar = %s of size %d" % [ar.class, ar.size]
ix=0
ar.each {|x| puts "Type of ar[#{ix}] is %s" % [ix, ar[ix].class]; ix+=1}


That resulted in:



Type of ar = Array of size 2
Type of ar[0] is 0
Type of ar[1] is 1



So it seem like we don't have an array of arrays. So what do we have? Or am I all wet?



Regards,
Richard

A programmer is a device for turning coffee into code.
Jeff Prosise (with an assist from Paul Erdos)
2 Answers

Hal E. Fulton

9/14/2003 8:51:00 AM

0

RLMuller wrote:
> Hi All,
>
> "Programming Ruby" says the following for String#scan at
> http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_string.html#S...:
>
>
> |a = "cruel world" |
>
> |...|
>
> |a.scan(/(..)(..)/) |» |[["cr", "ue"], ["l ", "wo"]]|
>
> ||
>
> |I wrote the following to test whether scan actually produced an array
> or arrays:|
>
> ||
>
> |a = "cruel world"
> ar = a.scan(/(..)(..)/)
> puts "Type of ar = %s of size %d" % [ar.class, ar.size]
> ix=0
> ar.each {|x| puts "Type of ar[#{ix}] is %s" % [ix, ar[ix].class]; ix+=1}
> |
>
> |That resulted in:|
>
> ||
>
> |Type of ar = Array of size 2
> Type of ar[0] is 0
> Type of ar[1] is 1|
>
> ||
>
> |So it seem like we don''t have an array of arrays. So what do we have?
> Or am I all wet?|

You''re all wet. ;)

Seriously, you''ve just made a typo or two. Your last format string does
an interpolation instead of using a format specifier. You''re printing
the value of ix as the class.

I suggest each_with_index and consistent formatting, like

ar.each_with_index {|x,ix| puts "Type of ar[#{ix}] is #{ar[ix].class}" }

If you don''t like variable interpolation, you can use a real printf:

printf "Type of ar[%d] is %s\n",ix,ar[ix].class

Anyhow, you do get real live arrays here, just as the Book says.

Hal


RLMuller

9/14/2003 5:06:00 PM

0

Many thanks, Hal,

As I told you before, I''ve got your book, but digesting everything in
a book of 579+ pages takes time, as does finding the answer to a
specific question, so thanks for hanging out on this newsgroup.

And thanks for ''drying me out''; I certainly was ''all wet'' in my
amateurish mistake. Better still, I''m thankful for your truly
Rubyesque improvement. I learned one more thing, thereby.

Regards,
Richard