Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I join by new line

Tags:

ruby

I am reading a file which has source code. I need to append 2 spaces before each line. This is what I am doing.

data = read_file data.split(/\n/).collect {|l| '  ' + l}.join('\n') 

However after joining when I do puts then it prints \n literally and it is not a line break. How do I fix that?

like image 233
Nick Vanderbilt Avatar asked Aug 23 '10 13:08

Nick Vanderbilt


People also ask

How do you add a new line to a string join?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you join a newline in Python?

To join a list with a newline character in Python: Call the join() method on a string containing a newline char ( '\n' ). Pass the list to the join method. The result will be a string containing the list items separated by a newline.

How do I join a new line array?

Convert array to string with newlines using join()The join('\r\n') method is used. '\r\n' is passed in as the method's argument that acts as a separator while converting the array to string values. The array elements are divided into newline using '\r\n'.

How do you break an array line?

To add a line break in array values for every occurrence of ~, first split the array. After splitting, add a line break i.e. <br> for each occurrence of ~.


1 Answers

You need to use a double quote (") instead of a single quote. So replace this:

'\n' 

with this:

"\n" 

Read more about it here.

You might want to use \r\n instead if you want your line-endings to be CRLF instead of LF (some Windows editors such as Notepad won't see a LF linebreak).

like image 151
Veeti Avatar answered Sep 28 '22 17:09

Veeti