190

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
  • 6
    The documentation is your friend! It will help you considerably to study the methods of Array, String, Hash, etc. Commented Oct 26, 2010 at 0:27

4 Answers 4

350

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

@arr.join(" ")
Sign up to request clarification or add additional context in comments.

4 Comments

what if you were joining digits? [1,2,3] => 123?
@mr.musicman join works with enumerables of anything that responds to to_s, including integers, but the result will always be a string. If you want an integer result, you can use to_i on the result.
If you initially broke up a multi-line string using String#lines, you can sanely tied it back together using my_string.join('') (note the empty string argument).
To add to what @sepp2k said: join tries #to_str first and #to_s second.
21

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

@arr * " "

2 Comments

besides being cryptic, is there any possible flaw when using this trick?
@marcioAlmada No flaw, just minimal overhead. In array.c the first thing Ruby does is checking for a string type and then calling the join method. Also: pry with show-source rocks! Try for yourself: $ Array.instance_methods.* ($ is shorthand for show-source)
3

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>

Comments

0

Another possible implementation for this would be the following:

I'm more used to #inject even though one can use #reduce interchangeably

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.inject(:+)
=> <p>Hello World</p><p>This is a test</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.