How to add extra newline with 'puts' witho

2019-04-17 21:15发布

问题:

If I say

puts "Hello"

and decide to add an extra newline I need to do this:

puts "Hello\n"

Having this character in the string is ugly. Is there any way to do this without polluting my string?

回答1:

Just make another call to puts:

puts "Hello"
puts


回答2:

puts "Hello",""


回答3:

I often find myself adding a constant in ruby to contain these characters

NEW_LINE = "\n"

puts "Hello" + NEW_LINE

I think it is more readable and makes a change to all newline characters easy if anyone ever decides to separate each line by something else at some later date.



回答4:

Do you think this looks nicer?


puts "Hello"+$/

</evil>



回答5:

The reason Ruby uses "\n" for a newline is because its based on C. Ruby MRI is written in C and even JRuby is written in Java which is based on C++ which is based on C... you get the idea! So all these C-style languages use the "\n" for the new line.

You can always write your own method that acts like puts but adds new lines based upon a parameter to the method.



回答6:

you can just write

p "Hello"
p 

That should work as well if you want to keep it short and simple



回答7:

Well, I don't think an explicit newline is ugly. mipadi's answer is just fine as well. Just to throw another answer in, make an array of the lines then join the aray with a newline. :)



回答8:

What you want fixed: input for script:

puts "Hello there"
puts "Goodbye"

Output from script:

Hello thereGoodbye

Fix for the problem: Input for script:

puts "Hello there"
puts
puts "Goodbye"

Output from script:

Hello there
Goodbye