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>
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.
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.
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.
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With