Home »
Ruby Tutorial
Creating Array with Array.new(size){|index|} in Ruby
By IncludeHelp Last updated : November 17, 2024
In the previous article, we have learned how we can declare an Array class instance with the help of the Array.new(Array) method? You can also notice that in the program codes written to demonstrate all those methods are having Array instances declared with the conventional method such as,
array_name = ['ele1', 'ele2', 'ele3', ..., 'eleN']
Now, after reading the previous articles, we have learnt to declare an Array class object in the following ways as well,
array_name = Array.[](*args)
array_name = Array.new(size = 0, obj = nil)
array_name = Array.new(size){|index| block}
The above is the way we have used it in the last articles. We have learned three ways through which we can declare an Array in Ruby till time. Well, in this article, we will see that how we can declare an Array object with the help of Array.new(size){|index| block} method.
Method Description
This method is a public class method. Earlier Arrays are created by passing an index to them. In the case of this method, the value of each element is generated by passing the index of the element to the provided block and the returned value is stored.
Syntax
array_name = Array.new(size){|index| index#operation}
Parameters
Arguments play a very important role in this method. This method will take the size as the Argument. Whole processing will be done with the help of the provided block.
Example 1
=begin
Ruby program to demonstrate the
Array.new(size){} method
=end
# array declaration
arr = Array.new(5){|index| index*2}
# printing array elements
puts "Array elements are..."
puts arr
Output
Array elements are...
0
2
4
6
8
Explanation
With the help of the above code, you can easily understand the implementation of the Array.new(size) method. We are creating an Array instance named "arr" with the help of this method. We want the Array object to be of size 5 and the elements should be of index multiple of 2. In the output, you can observe that the Array elements are 0, 2, 4, 6 and 8. The first element is 0 because we know that the indexing of an Array instance starts with 0 always. You can take input of the size from the user as well.
Example 2
=begin
Ruby program to demonstrate
the Array.new(size){} method
=end
# array declaration
arr = Array.new(5){|index|}
# printing array elements
puts "Array elements are..."
puts arr
Output
Array elements are...
Explanation
You can observe in the above code that when you are specifying the criteria through which you want to propagate the Array then nil values are assigned for size times. Here, five nil values are provided to the Array.