What is the array.join() function in Ruby?

Overview

Converting an array to a string is one thing, but separating the strings with a given separator is another.

This is very easy to implement in Ruby.

Using the join() method on an array converts the elements of the array to a string and separates them with the specified separator.

Syntax


array.join(separator)

Parameters

  • separator: This is the separator you want to use to separate each string.

Return value

The value returned is a string of elements of the original array that are separated by the specified separator.

Code

In the example below, we create different arrays and use the join() method on them.

# create arrays
arr1 = [10, 20, 30, 40, 50, 60]
arr2 = ["ab", "cd", "ef", "gh"]
arr3 = ["hu", "ra", "yy"]
arr4 = ["ye", "aa", "aa"]
arr5 = [true, false, 0, 1]
arr6 = ["merry", "go", "round"]
# convert to string and add separators
a = arr1.join("*")
b = arr2.join(",")
c = arr3.join("-")
d = arr4.join("-")
e = arr5.join("+")
f = arr6.join("-")
puts a
puts b
puts c
puts d
puts e
puts f

Free Resources