How to Combine Array to String in Ruby

MD Aminul Islam Feb 02, 2024
  1. Method 1: Use the join("") Function
  2. Method 2: Use the reduce(:+) Function
  3. Method 3: Use the inject(:+) Function
How to Combine Array to String in Ruby

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.

MD Aminul Islam avatar MD Aminul Islam avatar

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.

LinkedIn

Related Article - Ruby Array

Related Article - Ruby String