31

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?

1
  • 1
    Do you want a new array, or expand an existing array? Which? Commented May 30, 2013 at 8:15

8 Answers 8

48
def fixed_array(size, other)  
   Array.new(size) { |i| other[i] }
end
fixed_array(5, [1, 2, 3])
# => [1, 2, 3, nil, nil]
Sign up to request clarification or add additional context in comments.

1 Comment

Is this possible only for particular index ?
12
5.times.collect{|i| other[i]}
 => [1, 2, 3, nil, nil] 

Comments

5

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

Yes, you can expand your current array by setting the last element via Array#[]=:

a = [1, 2, 3]
a[4] = nil # index is zero based
a
# => [1, 2, 3, nil, nil]

A method could look like this:

def grow(ary, size)
  ary[size-1] = nil if ary.size < size
  ary
end

Note that this will modify the passed array.

Comments

4
a = [1, 2, 3]
b = a.dup
Array.new(5){b.shift} # => [1, 2, 3, nil, nil]

Or

a = [1, 2, 3]
b = Array.new(5)
b[0...a.length] = a
b # => [1, 2, 3, nil, nil]

Or

Array.new(5).zip([1, 2, 3]).map(&:last) # => [1, 2, 3, nil, nil]

Or

Array.new(5).zip([1, 2, 3]).transpose.last # => [1, 2, 3, nil, nil]

Comments

4

Similar to the answer by @xaxxon, but even shorter:

5.times.map {|x| other[x]}

or

(0..4).map {|x| other[x]}

1 Comment

or (0...5) (with three dots)
2

You can also do the following: (assuming other = [1,2,3])

(other+[nil]*5).first(5)
=> [1, 2, 3, nil, nil]

if other is [], you get

(other+[nil]*5).first(5)
=> [nil, nil, nil, nil]

Comments

1

this answer uses the fill method

def fixed_array(size, other, default_element=nil)
  _other = other
  _other.fill(default_element, other.size..size-1)
end

Comments

0

How about this? So you don't create a new array.

def fixed_array(size, other)
  (size - other.size).times { other << nil }
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.