Ruby Combining an Array into One String
In Ruby Is There a Way to Combine All Array Elements into One String? Example Array: @Arr = ['Hello World', 'This Is a Test'] Example Output: Hello Worldthis...
In Ruby is there a way to combine all array elements into one string?
Example Array:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
Example Output:
<p>Hello World</p><p>This is a test</p>
3 Answers
Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):
@arr.join(" ")
While a bit more cryptic than join, you can also multiply the array by a string.
@arr * " "
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>