Ruby Combining an Array into One String

Ruby Combining an Array into One String

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>
1

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(" ")
4

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

@arr * " "
2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.