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

后端 未结 7 1562
遥遥无期
遥遥无期 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: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.

提交回复
热议问题