89

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!

tatlar
  • 3,080
  • 2
  • 29
  • 40
jdimona
  • 1,227
  • 2
  • 9
  • 9

7 Answers7

94

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

Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
72

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.

Screamer
  • 1,141
  • 10
  • 13
18

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

(1..5).to_a.join("<br>").html_safe
Ajay
  • 4,199
  • 4
  • 27
  • 47
6

Try this also:

puts (1..4).to_a * "\n"
khelll
  • 23,590
  • 15
  • 91
  • 109
2

You may not want to use html_safe, like ajay said, depending on context. Html safe can be a security issue. This depends on if the original input was actually html safe. HTML safe should not be called on input direct from a user and typically should be called before the view.

https://bibwild.wordpress.com/2013/12/19/you-never-want-to-call-html_safe-in-a-rails-template/

[edited in response to comment below]

AMB
  • 315
  • 6
  • 14
  • Not necessarily. As the last line in the blog post says, **Code should never call html_safe on a string unless that code constructed the string and actually ensured it’s html-safety!**. Using `html_safe` *can* be ok, as long as you understand what it does and understand that there are security implications. Answers like this are unhelpful. – zelanix Jun 18 '16 at 15:54
  • I see now, just by coincidence, that you've edited the answer - that's great, and I agree with your new working. Just a note, if you reply to the comment, I can change my vote. – zelanix Sep 29 '16 at 12:00
  • However, as you now have your 50 rep, note that in future this would be more appropriate as a comment rather than an answer. – zelanix Sep 29 '16 at 12:02
1

As some of the other answers above imply, Rails may be escaping your code before rendering as html. Here's a sample that addresses this problem (first sanitizing the inputs, so that you can "safely" call html_safe on the result):

my_array = [1, 2, 3, 4]
my_array.map{ |i| i.to_s.sanitize }.join("\n").html_safe

You only need sanitize if you don't trust the inputs.

staxim
  • 1,328
  • 14
  • 15
0

How about this If you wanted to print each element on new line..

> a = [1, 2, 3, 4] 
> a.each{|e| puts e}
1
2
3
4
 => [1, 2, 3, 4] 
Hetal Khunti
  • 787
  • 1
  • 9
  • 23