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

后端 未结 7 1535
遥遥无期
遥遥无期 2020-12-29 01:44

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


        
相关标签:
7条回答
  • 2020-12-29 02:26

    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] 
    
    0 讨论(0)
  • 2020-12-29 02:30

    Try this also:

    puts (1..4).to_a * "\n"
    
    0 讨论(0)
  • 2020-12-29 02:31

    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.

    0 讨论(0)
  • 2020-12-29 02:32

    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.

    0 讨论(0)
  • 2020-12-29 02:35

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

    0 讨论(0)
  • 2020-12-29 02:35

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

    (1..5).to_a.join("<br>").html_safe
    
    0 讨论(0)
提交回复
热议问题