including newlines in a .sub

A

Alan Munn

Hi, I'm new to ruby, and am having trouble with the following (\n is
newline on a Mac).

e.g.

line = "foo bar"
line = line.sub(/ /, '\n')
puts line

This produces:

foo\nbar

when what I want (and expected) was:

foo
bar

(This is just a toy example; I don't actually want to split lines on
spaces.) What I don't understand is how to insert a true newline into a
string so that it outputs as such.

Thanks

Alan
 
S

Sebastian Hungerecker

Am Montag 20 Juli 2009 21:30:06 schrieb Alan Munn:
line = line.sub(/ /, '\n')

In ruby "\n" is a newline, while '\n' is backslash followed by an n.

HTH,
Sebastian
 
A

Alan Munn

Sebastian Hungerecker said:
Am Montag 20 Juli 2009 21:30:06 schrieb Alan Munn:

In ruby "\n" is a newline, while '\n' is backslash followed by an n.

Perfect. Thanks. I had tried that with my more complicated example
(which included reference to capture groups from the regex) and it
didn't work, but now I realise I need to concatenate the pieces together
with a mix of single and double quotes to get it to work.

Alan
 
S

Sebastian Hungerecker

Am Montag 20 Juli 2009 22:05:05 schrieb Alan Munn:
Perfect. Thanks. I had tried that with my more complicated example
(which included reference to capture groups from the regex) and it
didn't work, but now I realise I need to concatenate the pieces together
with a mix of single and double quotes to get it to work.

Well you could also use double quotes exclusively and use \\1, \\2 etc. to
refer to the captures.

HTH,
Sebastian
 
J

Jacky Cheung

[Note: parts of this message were removed to make it a legal post.]

2009/7/21 Ryan Davis said:
Ignore him. He's a dick.


you need to know some basic thing of programing


JackyCheung
 
X

Xavier Noria

J

Jacky Cheung

[Note: parts of this message were removed to make it a legal post.]

r u a programmer ? don't know '\n' is what mean???
 

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
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top