Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with a fixed size, and fill default content with another array?

Tags:

I want to create a fixed size array with a default number of elements already filled from another array, so lets say that I have this method:

def fixed_array(size, other)   array = Array.new(size)   other.each_with_index { |x, i| array[i] = x }   array end 

So then I can use the method like:

fixed_array(5, [1, 2, 3]) 

And I will get

[1, 2, 3, nil, nil] 

Is there an easier way to do that in ruby? Like expanding the current size of the array I already have with nil objects?

like image 816
rorra Avatar asked May 30 '13 08:05

rorra


People also ask

How do you create an array of fixed lengths?

Use a tuple to declare an array with fixed length in TypeScript, e.g. const arr: [string, number] = ['a', 1] . Tuple types allow us to express an array with a fixed number of elements whose types are known, but can be different. Copied! We declared a tuple with 3 elements with types of string , number and number .

How do you fix the size of an array?

Size of an array If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.

Can you declare an array without assigning the size of an array?

Answer: No. It is not possible to declare an array without specifying the size. If at all you want to do that, then you can use ArrayList which is dynamic in nature.

How do you set the size of an array in Python?

Initializing array using python NumPy Module NumPy module can be used to initialize the array and manipulate the data stored in it. The number. empty() function of the NumPy module creates an array of a specified size with the default value=” None”.


1 Answers

def fixed_array(size, other)      Array.new(size) { |i| other[i] } end fixed_array(5, [1, 2, 3]) # => [1, 2, 3, nil, nil] 
like image 118
toro2k Avatar answered Oct 14 '22 11:10

toro2k