Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

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

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

array
ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring