What is the array.to_s function in Ruby?

Overview

Arrays in Ruby can be represented as a string. This is possible with the array.to_s() function in Ruby, which creates a string representation of an array.

Syntax

array.to_s

Parameters

This function takes no parameters.

Return value

The value returned is a string representation of the array.

Code

In the code below, several arrays are created and the string representation, using the to_s function, is printed to the console.

# creating arrays
languagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]
numbersArray = [1, 2, 3, 4, 5]
alphabetsArray = ["a", "b", "c", "d", "e"]
booleanArray = [true, false]
animalsArray = ["dog", "cat", "rat", "cow", "bat"]
# print string representations
puts languagesArray.to_s
puts numbersArray.to_s
puts alphabetsArray.to_s
puts booleanArray.to_s
puts animalsArray.to_s

Free Resources