Read more

Ruby: How to grow or shrink an array to a given size

Arne Hartherz
April 20, 2015Software engineer at makandra GmbH

If you want to grow a Ruby Array, you might find out about #fill but it is not really what you are looking for. [1]
For arrays of unknown size that you want to grow or shrink to a fixed size, you need to define something yourself. Like the following.

Array.class_eval do

  def in_size(expected_size, fill_with = nil)
    sized = self[0, expected_size]
    sized << fill_with while sized.size < expected_size
    sized
  end

end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Use it like this:

>> [1, 2, 3].in_size(5)
=> [1, 2, 3, nil, nil]
>> [1, 2, 3, 4, 5, 6, 7].in_size(5)
=> [1, 2, 3, 4, 5]

Attached you will find the above method definition of #in_size. Put it in where your monkey-patches live.
You will also find a spec that goes along with it.


[1] Array#fill does the job but is really meant for writing ranges inside an array. Its syntax is a bit weird to use for growing (e.g. to get from [1, 2, 3] to [1, 2, 3, "foo", "foo"] you have to say [1, 2, 3].fill("foo", 3..4) or [1, 2, 3].fill("foo", 3, 2) which are both equally odd-looking) and while we could use it inside our #in_size method it would not make things easier.

Posted by Arne Hartherz to makandra dev (2015-04-20 11:33)