187

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>
Termininja
  • 6,620
  • 12
  • 48
  • 49
dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189
  • 6
    The documentation is your friend! It will help you considerably to study the methods of Array, String, Hash, etc. – Mark Thomas Oct 26 '10 at 00:27

4 Answers4

346

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

@arr.join(" ")
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 1
    what if you were joining digits? `[1,2,3] => 123`? – stevenspiel Dec 09 '13 at 19:08
  • 3
    @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. – sepp2k Dec 09 '13 at 20:21
  • 1
    If you initially broke up a multi-line string using [`String#lines`](http://ruby-doc.org/core-2.2.0/String.html#method-i-lines), you can sanely tied it back together using `my_string.join('')` (note the empty string argument). – Frank Koehl Feb 26 '15 at 20:20
  • To add to what @sepp2k said: `join` tries `#to_str` first and `#to_s` second. – Greg Navis Dec 17 '16 at 11:08
21

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

@arr * " "
David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • 1
    besides being cryptic, is there any possible flaw when using this trick? – marcio Mar 04 '14 at 23:41
  • 4
    @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) – okket Mar 16 '14 at 00:17
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>
Claire Nielsen
  • 1,881
  • 1
  • 14
  • 31
von spotz
  • 875
  • 7
  • 17
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>
Jose Paez
  • 747
  • 1
  • 11
  • 18