Creating Array with Array.new(size, obj) in Ruby

In this example we are going to create array with two arguments in Ruby
Size: Size of array we are going to create
object: The element we are going to store in Array.

Syntax

array_name = Array.new(size = 0, obj = nil);

 

Example 

# array declaration

arr1 = Array.new(size = 5, obj = "Ruby")

 

# printing array elements

puts "Elements of \'arr1\' are:"

puts arr1

 

# creating an empty array

arr2 = Array.new()

puts "Number of elements present in \'arr2\' are: #{arr2.count}"

 

Output

Elements of 'arr1' are:
Ruby
Ruby
Ruby
Ruby
Ruby
Number of elements present in 'arr2' are: 0

 


Subscribe For Daily Updates

Flutter Questions
Android Questions