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.
array.join(separator)
separator
: This is the separator you want to use to separate each string.The value returned is a string of elements of the original array that are separated by the specified separator.
In the example below, we create different arrays and use the join()
method on them.
# create arraysarr1 = [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 separatorsa = arr1.join("*")b = arr2.join(",")c = arr3.join("-")d = arr4.join("-")e = arr5.join("+")f = arr6.join("-")puts aputs bputs cputs dputs eputs f