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.
for i in var
i.to_s
puts i
end
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.
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:
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.
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:
Closing
This short guide has used examples to illustrate how to convert elements in an array to a string.