Convert Array to String in Ruby

Stewart Nguyen Jan 02, 2022
  1. Use to_s to Convert an Array to String in Ruby
  2. Use inspect to Convert an Array String in Ruby
  3. Use join and map to Convert an Array to String for Complex Output Format in Ruby
Convert Array to String in Ruby

Given an array, for example ['12', '34', '56']. How to convert it into string in ruby?

Use to_s to Convert an Array to String in Ruby

to_s is a common built-in method available for array type and most ruby data types, including hash, number, or even boolean. The returned value has the type of string.

['12', '34', '56'].to_s

Output:

"[\"12\", \"34\", \"56\"]"

We may find the output format looks complex, but it’s pretty nice when printing.

puts ['12', '34', '56'].to_s

Output:

["12", "34", "56"]

When we interpolate an array into a string, it will call to_s under the hood.

array = ['12', '34', '56']
string = "My array: #{array}"
puts string

Output:

My array: ["12", "34", "56"]

Use inspect to Convert an Array String in Ruby

inspect returns a human-readable string for any object in ruby, and it can be used in place of to_s.

puts ['12', '34', '56'].inspect

Output:

["12", "34", "56"]

Use join and map to Convert an Array to String for Complex Output Format in Ruby

How to convert ['12', '34', '56'] into a string with format '12','34','56'?

As we can see, both to_s and inspect return extra square brackets, spaces, and use the double quote (") instead of single quote (')

To accomplish it, we could combine join and map to convert an array into a string with a customized output format.

First, use Array#join to add a delimeter between the array’s items.

['12', '34', '56'].join("','")

Output:

"12','34','56"

Second, use string interpolation to surround the temporary result inside a pair of single quotes.

delimeter_added_string = ['12', '34', '56'].join("','")
result = "'#{delimeter_added_string}'"
puts result

Output:

=> '12','34','56'

Related Article - Ruby Array

Related Article - Ruby String