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.
array.fill(e)# Based on Rangearray.fill(e,start..end)# Based on Lengtharray.fill(e, start, length)# Based on Blockarray.fill {|index| block}
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.
A new array is returned that contains elements that fill the array.
We shall demonstrate the fill()
method using the different techniques introduced above in the following examples.
In the example below, we shall fill an array with a single element:
# create an arrayarr = [1, 2, 3, 4, 5]# fill arraya = arr.fill(10);# print out filled arrayputs "#{a}";
In the example below, we shall fill an array by specifying the range.
# create an arrayarr = ["a", "b", "c", "d"]# fill by rangea = arr.fill("x", 2..4) # fill from position 2 to 4# print returned valueputs "#{a}"
In the code sample above, 2..4
means fill z
from index position 2
till 4
.
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 arrayarr = [1, 2, 3, 4, 5]# fill array by lengtha = arr.fill("0", 1, 3);# print out returned valueputs "#{a}";
The fill()
method above means fill array arr
with 0
from index position 1
for 3 times.
In the example below, we shall fill an array by using a block:
# create an arrayarr = [1, 2, 3, 4, 5]# fill by blocka = arr.fill {|index| index * 2 }# print returned valueputs "#{a}"
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.