New line in string

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

On Tue, Oct 6, 2009 at 11:23 AM, Sharanya S.
[email protected] wrote:

How it can be done?
You nearly got it:

str = “hello”;
str += “\n”;
str += “world”

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

irb(main):006:0> “\n”.size
=> 1
irb(main):007:0> ‘\n’.size
=> 2

Hope this helps,

Jesus.

2009/10/6 Jesús Gabriel y Galán [email protected]:

world
How it can be done?

You nearly got it:

str = “hello”;
str += “\n”;
str += “world”

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

irb(main):012:0> str = “hello”
=> “hello”
irb(main):013:0> str << “\n”
=> “hello\n”
irb(main):014:0> str << “world”
=> “hello\nworld”

The previous idiom (+=) creates new strings.

Jesus.

Hi,

Am Dienstag, 06. Okt 2009, 18:32:26 +0900 schrieb Jesús Gabriel y Galán:

str = “hello”
str << “\n”
str << “world”
#=> “hello\nworld”

The previous idiom (+=) creates new strings.

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

%w(hello world).join $/

Bertram

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs