rubyarrayspadding

Method for padding an array in Ruby


Here's what I have now and it is somewhat working:

def padding(a, b, c=nil)
  until a[b-1]
    a << c
  end
end

This is when it works:

a=[1,2,3]
padding(a,10,"YES")
=>[1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]

a[1,2,3]
padding(a,10,1)
=>[1, 2, 3, 1, 1, 1, 1, 1, 1, 1]

But it crashes when I do not enter a value for "c"

a=[1,2,3]
padding(a,10)
Killed

How should I append this to avoid a crash? Additionally, how would you suggest changing this method to use it as follows:

[1,2,3].padding(10)
=>[1,2,3,nil,nil,nil,nil,nil,nil,nil]
[1,2,3].padding(10, "YES")
=>[1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]

I've seen other padding methods on SO, but they don't seem to be working as intended by the authors. So, I decided to give making my own a shot.


Solution

  • It is killed, because you are entering infinite loop. until a[b-1] will not finish, because when you add nils to the array, you will get:

    a == [1, 2, 3, nil, nil, nil, nil, nil, nil, nil]
    

    after few iterations and a[b-1] will be nil, which is falsey. Until will never stop.

    About the second question, it is easy to extend existing Array class:

    class Array
      def padding(i, value=nil)
        (i - length).times { self << value }
        self
      end
    end
    

    Result as you expected:

    [1,2,3].padding(10)
    #=> [1, 2, 3, nil, nil, nil, nil, nil, nil, nil]
    [1,2,3].padding(10, "YES")
    #=> [1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]
    

    Note the method about modifies existing array (so due to Ruby conventions should be called padding!):

    a = [1,2,3]
    #=> [1, 2, 3]
    a.padding(10, "YES")
    #=> [1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]
    a
    #=> [1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]
    

    But of course you can easy create the version of the method which doesn't modify. I assumed you want to modify the array, because your original method did it.