How to Combine Array to String in Ruby
-
Method 1: Use the
join("")
Function -
Method 2: Use the
reduce(:+)
Function -
Method 3: Use the
inject(:+)
Function
Sometimes we need to convert the full array into a string. This could be required for various purposes.
For example, you may have an array containing the first and last names of a user. So to get their full name, you need to combine the array elements.
This article will show how we can combine the array elements into one single string in Ruby. Also, we will see relevant examples to make it clearer.
In this article, we will discuss three different methods for this purpose.
Method 1: Use the join("")
Function
In our example below, we will demonstrate how we can combine array elements using the join()
function. Here are the lines of code that you can follow.
@MyArray = %w[This is an array]
myStr = String.new(@MyArray.join(' '))
puts "#{myStr}"
Here, we’ve provided space as a parameter of the join()
function. This will include a space between all the array elements.
You can use another character, too, based on your requirements.
After running the program above, you will get the output below.
This is an array
Method 2: Use the reduce(:+)
Function
In our example below, we will see how we can combine array elements using the reduce(:+)
function. Here are the lines of code that you can follow.
@MyArray = ['This ', 'is ', 'an ', 'array']
myStr = String.new(@MyArray.reduce(:+))
puts "#{myStr}"
Please note that the function reduce(:+)
won’t include any special character between the array elements. So we need to pre-include it in our array elements.
After running the program above, you will get the output below.
This is an array
Method 3: Use the inject(:+)
Function
In our below example, we will illustrate how we can combine array elements using the inject(:+)
function. Here are the lines of code that you can follow.
@MyArray = ['This ', 'is ', 'an ', 'array']
myStr = String.new(@MyArray.inject(:+))
puts "#{myStr}"
Please note that the function reduce(:+)
won’t include any special character between the array elements. So we need to pre-include it in our array elements.
After running the program above, you will get the output below.
This is an array
Please note that all the codes this article shares are written in Ruby.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedInRelated Article - Ruby Array
- %i and %I in Ruby
- How to Square Array Element in Ruby
- How to Merge Arrays in Ruby
- How to Convert Array to Hash in Ruby
- How to Remove Duplicates From a Ruby Array