Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
string
ruby
communitycreator

How to concatenate array elements with a string using * in Ruby

okwudili onyejiaku

When you want to concatenate array elements with a string, you can use the array.join() method or * operator for this purpose.

For this shot, we will be using the * operator to concatenate elements of an array with a string.

Syntax

array * string

Parameters

array: This is the array of which elements we want to concatenate with a string.

Return value

The value returned is a new array by concatenating the elements of the original array with string.

Example

In the example below, we created several arrays. We called the * operator on each array together with a string in order to concatenate the array elements with the string.

# create arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Ruby", "Java", "JavaScript", "Python"]
arr4 = ["1ab", "2cd", "3ef", "4gh", "5ij"]
arr5 = [nil, "nil", "true", "false", true]

# concatenate elements of arrays with strings
# using the `*` operator
a = arr1 * "-"
b = arr2 * "|"
c = arr3 * "+"
d = arr4 * "xxx"
e = arr5 * ","

# print retured values
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"
Concatention of array with string

RELATED TAGS

array
string
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring