开发者

Ruby combining an array into one string

开发者 https://www.devze.com 2023-01-22 10:25 出处:网络
In Ruby is there a way to combine all array elements into one string? Example Array: @arr = [\'<p&g开发者_StackOverflow中文版t;Hello World</p>\', \'<p>This is a test</p>\']

In Ruby is there a way to combine all array elements into one string?

Example Array:

@arr = ['<p&g开发者_StackOverflow中文版t;Hello World</p>', '<p>This is a test</p>']

Example Output:

<p>Hello World</p><p>This is a test</p>


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

@arr.join(" ")


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

@arr * " "


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>


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消