[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Doubts on char patterns into String.each argument

Carlos Ortega

8/5/2007 11:43:00 PM

Hello Folks with a question I would like someone can clarify me:

When I type the following code:

"Substring1 Substring2 Substring3".each( '\s*' ) { | substring |
puts "[" + substring +"]"
}

What I got is:

[Substring1 ]
[Substring2 ]
[Substring3]


However when I type:

"Substring1 Substring2 Substring3".each( '\s*' ) { | substring |
puts "[" + substring +"]"
}

What I got is:

[Substring1 Substring2 Substring3]


Why the difference in outputs?
I verified in the "Programming Ruby 2nd (Dave Thomas - 2005)"
and it says that the ' ' is just one of the White Characters
that '\s' may represent ( the other ones are TAB and NEW LINE)

Any help would be very appreciated.
--
Posted via http://www.ruby-....

3 Answers

Nobuyoshi Nakada

8/6/2007 12:50:00 AM

0

Hi,

At Mon, 6 Aug 2007 08:43:07 +0900,
Carlos Ortega wrote in [ruby-talk:263437]:
> When I type the following code:
>
> "Substring1 Substring2 Substring3".each( '\s*' ) { | substring |
> puts "[" + substring +"]"
> }

What differs?

> However when I type:
>
> "Substring1 Substring2 Substring3".each( '\s*' ) { | substring |
> puts "[" + substring +"]"
> }

--
Nobu Nakada

Ken Bloom

8/6/2007 12:54:00 AM

0

On Mon, 06 Aug 2007 08:43:07 +0900, Carlos Ortega wrote:

> "Substring1 Substring2 Substring3".each( '\s*' ) { | substring |
> puts "[" + substring +"]"
> }

In ruby, if you want something to be interpreted as a regular expression,
you must declare it as a regular expression. Hence /\s*/ would be
correct. Except that each() only accepts strings, so you can't use a
regular expression with it.

Use
"Substring1 Substring2 Substring3".split(/\s+/).each{|x| puts x}
instead

--
Ken Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu...

David A. Black

8/6/2007 2:00:00 AM

0