new line in string

  • Thread starter Sharanya Suresh
  • Start date
S

Sharanya Suresh

Hi,

How to concatenate new line character to a string?

Eg: str = "hello";
str += '\n';
str += "world"
I must get
hello
world
How it can be done?


Thanks in advance

Sharanya
 
J

Jesús Gabriel y Galán

Hi,

How to concatenate new line character to a string?

Eg: str =3D "hello";
=A0 =A0str +=3D '\n';
=A0 =A0str +=3D "world"
I must get
hello
world
How it can be done?

You nearly got it:

str =3D "hello";
str +=3D "\n";
str +=3D "world"

You just need to use double quotes. Single quotes don't interpret
special characters:

irb(main):006:0> "\n".size
=3D> 1
irb(main):007:0> '\n'.size
=3D> 2

Hope this helps,

Jesus.
 
J

Jesús Gabriel y Galán

2009/10/6 Jes=FAs Gabriel y Gal=E1n said:
You nearly got it:

str =3D "hello";
str +=3D "\n";
str +=3D "world"

BTW, if you want to concatenate to the same object, instead of
creating a new one, use this:

irb(main):012:0> str =3D "hello"
=3D> "hello"
irb(main):013:0> str << "\n"
=3D> "hello\n"
irb(main):014:0> str << "world"
=3D> "hello\nworld"

The previous idiom (+=3D) creates new strings.

Jesus.
 
B

Bertram Scharpf

Hi,

Am Dienstag, 06. Okt 2009, 18:32:26 +0900 schrieb Jes=FAs Gabriel y Gal=E1n:
2009/10/6 Jes=FAs Gabriel y Gal=E1n said:
=20
BTW, if you want to concatenate to the same object, instead of
creating a new one, use this:
=20
str =3D "hello"
str << "\n"
str << "world"
#=3D> "hello\nworld"
=20
The previous idiom (+=3D) creates new strings.

Depending on what you're doing maybe this is a good choice:

%w(hello world).join $/

Bertram


--=20
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-scharpf.de
 

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,167
Messages
2,570,910
Members
47,453
Latest member
MadelinePh

Latest Threads

Top