Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

What is array * int in Ruby?

okwudili onyejiaku

Overview

The array * int is a way by which arrays are modified. The * when used with int, an integer, returns a new array with the int copies of the original array’s elements.This means that if there is an array that contains [a,b], then [a,b] * 2 will return a new array as [a,b,a,b].

Syntax

array * int

Parameters

array: this is the original array that we want to replicate its elements in a new array.

int: this is an integer value representing the number of times the elements in the original array, array, will replicate itself.

Return value

The value returned is a new array that concatenates the copies or elements of the original array.

A number of times equal to the value of the int.

Example

In the example below, several arrays were created and, their elements were replicated using the * operator.

# 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]

# replicate elements in the arrays
a = arr1 * 3    # replicate three times
b = arr2 * 1    # replicate once
c = arr3 * 2    # replicate two times
d = arr4 * 1    # replicate one time
e = arr5 * 4    # replicate four times

# Print returned arrays to console
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

Note that a negative int will return an empty array. See example below:

# create an array
array = [1, 2, 3, 4, 5]

# replicate elements zero times
a = array * 0

# print returned array
puts "#{a}"   # [] : empty array

Finally, a negative int will throw an error, see example below:

# create an array
array = [1, 2, 3, 4, 5]

# replicate elements zero times
a = array * -1

# print returned array
puts "#{a}"   # error will be thrown

RELATED TAGS

array
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring