Ruby combining an array into one string

后端 未结 3 695
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 08:39

In Ruby is there a way to combine all array elements into one string?

Example Array:

@arr = [\'

Hello World

\', \'

This is a

相关标签:
3条回答
  • 2020-12-02 09:19

    Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

    @arr.join(" ")
    
    0 讨论(0)
  • 2020-12-02 09:33

    While a bit more cryptic than join, you can also multiply the array by a string.

    @arr * " "
    
    0 讨论(0)
  • 2020-12-02 09:39

    Here's my solution:

    @arr = ['<p>Hello World</p>', '<p>This is a test</p>']
    @arr.reduce(:+)
    => <p>Hello World</p><p>This is a test</p>
    
    0 讨论(0)
提交回复
热议问题