Ruby fill array method

In ruby programming language, fill() array method are used to fill particular object to specified element in array. This method works on variety of syntax. Its syntax as follows.

fill(object) → array
fill(object, range) → array
fill(object, start [, length]) → array
fill {|index| block} → array

Ruby fill() method

In this section are mention few examples which is describes the functionality of fill() method such as how to use and how it will work. Let's see an example which is based on single and two parameters.

# Our arrays
r1  = ['a','b','c','d','e']
r2  = [1,2,3,4]
r3  = [1,2,3]

# fill operation
# When One or two parameters
r1.fill("x",2)
r2.fill("x",-2)
r3.fill(10)

# After result
print(" r1 : ",r1)
print("\n r2 : ",r2)
print("\n r3 : ",r3)
Ruby fill method example 1
 r1 : ["a", "b", "x", "x", "x"]
 r2 : [1, 2, "x", "x"]
 r3 : [10, 10, 10]

When given single object then this method are puts this object to each array elements. When given of two parameter value in this case first indicates fill objects element and second parameter values indicate starting index. When object is collection or enumerator so that is shared.

# Our array
record  = ['a','b','c','d','e']

# When filling collection and objects
record.fill([1,2],2)


# After result
print(" record : ",record)
Ruby fill method example 2
record : ["a", "b", [1, 2], [1, 2], [1, 2]]

We can test several conditions within a block statement. And decide what kind of result we need. For example. In given below some useful example to work in special cases.

# Our array
record  = [1,2,3,9,4]

# Fill with block operation
# Check whether element is even or odd
record.fill{|x| record[x] % 2 == 0}

# After result
print(" record : ",record)
 record : [false, true, false, false, true]
# Our array
record  = [1,2,3,4,5,8,9]

# Fill with start index [2] and length is 4
record.fill(true,2,4)

# After result
print(" record : ",record)
record : [1, 2, true, true, true, true, 9]
# Our array
record  = [1,2,3,4,5,8,9]

# Fill with index [2,4]
record.fill(true,2..4)

# After result
print(" record : ",record)
 record : [1, 2, true, true, true, 8, 9]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved