Wednesday, April 13, 2011

How to add extra newline with 'puts' without sticking newline character into string?

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?

From stackoverflow
  • Just make another call to puts:

    puts "Hello"
    puts
    
  • 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. :)

  • Do you think this looks nicer?

    
    puts "Hello"+$/
    

    </evil>

  • The reason why Ruby use \n for a newline is because its base on C where Ruby MRI is written in C and even JRuby is written in Java which is base on C++ which is base 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 act like puts but add new lines base upon a parameter to the method.

  • puts "Hello",""
    

0 comments:

Post a Comment