Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby combining an array into one string

Tags:

ruby

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>
like image 451
dennismonsewicz Avatar asked Oct 09 '22 22:10

dennismonsewicz


People also ask

How do I convert an array of strings to one string in Ruby?

In Ruby, we can convert an array into a string using the join method. The join method takes the array and a separator as the arguments. It then separates the elements in the array using the specified separator value.

How do I combine array elements into strings?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do you join elements in an array in Ruby?

Ruby | Array class join() function join() is an Array class method which returns the string which is created by converting each element of the array to a string, separated by the given separator. Example #1: Ruby.


1 Answers

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

@arr.join(" ")
like image 340
sepp2k Avatar answered Oct 11 '22 11:10

sepp2k