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.
Do you know
Array#fill
method :-It does, what you exactly looking for. If it exist, why you want your own.
You can fill your array, whatever way you want. It is a cool implementation. Give it a try.
Read it in your console :
Arup has nailed it, but here's another way:
To specifically implement your
padding
method on Array:EDIT: Forgot about
Array#fill
. Arup's answer is cool (even if you need to sayfill(3, 7)
instead offill(-1, 10)
, as the latter gives the wrong result). It would have been better to use it instead ofconcat(Array.new(...))
. Eh well. :)The problem is that nil is evaluated as false, so
until a[b-1]
is never true when a[b-1] contains nil... so you loop forever until you're out of memory.better to do...
EDIT (yes, Arup's answer is pretty neat)
You can do this as a one-liner, which is a bit more compact...
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: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:
Result as you expected:
Note the method about modifies existing array (so due to Ruby conventions should be called
padding!
):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.