Doubts on char patterns into String.each argument

C

Carlos Ortega

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

Nobuyoshi Nakada

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 +"]"
}
 
D

dblack

Hi --

"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

You could also just do:

puts "Substring1 Substring2 Substring3".split(' ')

You could even leave off the (' '), except then if $; has a value
you'd end up splitting on that.


David

--
* Books:
RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
& consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,318
Members
47,998
Latest member
GretaCjy4

Latest Threads

Top