Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.join("\n") not the way to join with a newline?

I have an array..

[1,2,3,4] 

and I want a string containing all the elements separated by a newline..

1  2  3  4 

but when I try [1,2,3,4].join("\n") I get

1\n2\n3\n4 

I feel like there is an obvious answer but I can't find it!

like image 504
jdimona Avatar asked Sep 19 '09 16:09

jdimona


People also ask

How do you join an array with a line break?

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 join a new line in JavaScript?

A New Console Output Line Will Be Added If you wish to add a new line to the JavaScript new line console while printing a few words, the \n sign for the new line can be used.

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 ~.

How do you join an array with spaces?

To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr. join(' ') . The join method returns a string with all array elements joined by the provided separator.


2 Answers

Yes, but if you print that string out it will have newlines in it:

irb(main):001:0> a = (1..4).to_a => [1, 2, 3, 4] irb(main):002:0> a.join("\n") => "1\n2\n3\n4" irb(main):003:0> puts a.join("\n") 1 2 3 4 

So it does appear to achieve what you desire (?)

like image 52
Cody Caughlan Avatar answered Sep 30 '22 14:09

Cody Caughlan


A subtle error that can occur here is to use single quotes instead of double. That also has the effect of rendering the newlines as \n. So

puts a.join("\n")   # correct 

is not the same as

puts a.join('\n')   # incorrect 

There is an excellent write up on why this is the case here.

like image 29
Screamer Avatar answered Sep 30 '22 12:09

Screamer