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

Solution 1:

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 (?)

Solution 2:

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.

Solution 3:

Just in case anyone searching for this functionality in ERB template then try this :

(1..5).to_a.join("<br>").html_safe