LuminaChen
LuminaChen

Reputation: 135

How to insert a newline character to an array of characters

I want to insert a newline character into an array of characters which initially is a string. Let's say I have a variable myvar = "Blizzard". A string is formed from an array of characters. How can I insert a newline character inside it? In hope of making an output like this:

"B
 lizzard"

I tried this:

myvar[1] = "\n"

but it's not working, and the output is like this:

"B\nlizzard"

My goal is to make the output like this:

B
l
i
z
z
a
r
d

without using puts. I have to do it by inserting newline characters into the array. Can someone point out where my mistake is, and if possible help me with this?

Upvotes: 2

Views: 5979

Answers (3)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

To add \n you can use this:

myvar = "Blizzard"
myvar.chars.map { |c| c + "\n" }.join.strip

Or better @Uri solution:

myvar.chars.join "\n"

But you can puts letters one on the line with next code:

myvar.chars.each { |c| puts c }

or:

myvar.each_char { |c| puts c } # for ruby >= 2.0

by Darek Nędza

Upvotes: 2

sawa
sawa

Reputation: 168081

You have done myvar[1] = "\n" correctly. Your problem is not how you did it, but what you are expecting.

You seem to be confusing the inspection of a string and the puts output of the string. Inspection is what is displayed as the return value as in irb, and it is a meta-representation of what you have. And as long as it is a string, it will be delimited by double quotes, and all the special characters will be escaped with a backslash \. If you have a new line character, that would be represented as "\n". On the other hand, when you pass the string to puts, you will get the output according to what the special characters represent.

What you displayed as what you want (the one in multiple lines) should be the result of puts. You will never get such thing as inspection of the string.

Upvotes: 2

Uri Agassi
Uri Agassi

Reputation: 37409

'Blizzard'.chars.join("\n")
# => "B\nl\ni\nz\nz\na\nr\nd" 

If all you want is to print the characters each in a new row you can do the following:

puts 'Blizzard'.chars

Output:

B
l
i
z
z
a
r
d

Upvotes: 2

Related Questions