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

Posted . Visible to the public.

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

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.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2015-04-20 09:33)