Ruby combining an array into one string

Ruby

Ruby Problem Overview


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>

Ruby Solutions


Solution 1 - Ruby

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

@arr.join(" ")

Solution 2 - Ruby

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

@arr * " "

Solution 3 - Ruby

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondennismonsewiczView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - RubyDavid HarknessView Answer on Stackoverflow
Solution 3 - Rubyvon spotzView Answer on Stackoverflow