Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
fill
ruby
communitycreator

What is array.fill() in Ruby?

okwudili onyejiaku

In Ruby, fill() is a Ruby method that is used to fill an array with a specified element. The element can also be made to fill an array based on a specific range, length, or block.

Syntax

array.fill(e)
# Based on Range
array.fill(e,start..end)
# Based on Length
array.fill(e, start, length)
# Based on Block
array.fill {|index| block}
Syntax of array.fill

Parameters

e: this represents an element in the array.

start..end: this is the range specified.

start: this is the starting index position.

length: this is the length to fill in an array.

index: this represents the index of each element.

block: this takes each element index of the array and passes it to the block.

Return value

A new array is returned that contains elements that fill the array.

Code example

We shall demonstrate the fill() method using the different techniques introduced above in the following examples.

Fill by element

In the example below, we shall fill an array with a single element:

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

# fill array
a = arr.fill(10);

# print out filled array
puts "#{a}";
Fill by element example

Fill by range

In the example below, we shall fill an array by specifying the range.

# create an array
arr = ["a", "b", "c", "d"]

# fill by range
a = arr.fill("x", 2..4)  # fill from position 2 to 4

# print returned value
puts "#{a}"
Fill by range example

In the code sample above, 2..4 means fill z from index position 2 till 4.

Fill by length

In the example below, we shall fill the array based on the length specified for the value that we want to use to fill the array.

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

# fill array by length
a = arr.fill("0", 1, 3);

# print out returned value
puts "#{a}";
Fill by length example

The fill() method above means fill array arr with 0 from index position 1 for 3 times.

Fill by block

In the example below, we shall fill an array by using a block:

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

# fill by block
a = arr.fill {|index| index * 2 }

# print returned value
puts "#{a}"
Fill by block example

The block method takes the index of each element and passes it to its corresponding function and fills the array with the returned value. In this case, we multiplied the index of the elements by 2. The result was used to fill the array.

RELATED TAGS

array
fill
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring