In Ruby, to convert an array to a string, we can use the join method. We can use the join method without any arguments or pass one that will act as our string delimiter.
some_array.join
Let’s see this with a full-code example.
some_array = ["red","blue","green","yellow","pink","black"]
some_array = some_array.join
print some_array
#Output
redbluegreenyellowpinkblack
Remember the p command will return what value the new output is. So just to confirm:
some_array = ["red","blue","green","yellow","pink","black"]
some_array = some_array.join
p some_array
#Output
"redbluegreenyellowpinkblack"
Here we can see that the output is indeed a string.
Finally, if we want to space out each word in the new string, we just have to add an argument to the join method.
some_array = ["red","blue","green","yellow","pink","black"]
some_array = some_array.join(", ")
print some_array
#Output
red, blue, green, yellow, pink, black
When using various programming languages, the ability to be able to convert variables from one variable type to another is very valuable. Many programming languages have the method tostring() to be able to get a string representation of a variable.
Ruby has the join method which will change an array object into a string object.
Below are some examples in Ruby of converting various arrays to strings with join. We will also print them using the p command to see that they have indeed been converted to strings.
some_array = ["red","blue","green","yellow","pink","black"]
some_array1 = ["string",true,"23",nil,"a short string"]
some_array2 = [{"first_name" => "Tom", "last_name" => "Smith" }]
some_array = some_array.join(", ")
some_array1 = some_array1.join(", ")
some_array2 = some_array2.join(", ")
puts some_array
puts some_array1
puts some_array2
#Output
red, blue, green, yellow, pink, black
string, true, 23, , a short string
{"first_name"=>"Tom", "last_name"=>"Smith"}
p some_array
p some_array1
p some_array2
#Output
"red, blue, green, yellow, pink, black"
"string, true, 23, , a short string"
"{"first_name"=>"Tom", "last_name"=>"Smith"}"
Hopefully this article has been useful for you to learn how to use Ruby to convert an array to a string.