jdimona jdimona - 2 months ago 8
Ruby Question

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!

Answer

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

Comments