Ruby Convert Array to String

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.

This quick guide will show various examples of converting an array to a string using the Ruby join method.

Example 1

Suppose we have an array of integers, and we want to convert each element in the array to a string.

The example below shows how we can perform such a task using a simple for loop.

var = [1,2,3,4,5]
for i in var
   puts i

In the example above, we implement a for loop that iterates over each item in the array. We then pass each item to the to_s method that converts it to a string.

Example 2

The next example uses the join method to separate elements in an array to individual string values.

var = [1,2,3,4,5]
puts var.join(", ")

In this example, we use the join method to separate each array element into a literal string. We use a comma and space as the delimiter.

Example 3

If you want to combine all the elements in the array into a single string value, you can specify the delimiter as:

var = [1,2,3,4,5]
puts var.join("")

The example shown above will return all the elements in the array combined into a single string value.

Example 4

We can also use the split method to convert a string to an array.

print "Ruby is a fun programming language".split

Ruby takes the delimiter specified in the split method and divides the string into equal blocks on the matching argument.

If no delimiter is specified, Ruby will use whitespace as the default value. The resulting array is as shown:

["Ruby", "is", "a", "fun", "programming", "language"]


This short guide has used examples to illustrate how to convert elements in an array to a string.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list