Feature #21284
openRequest: add `Array#pad` method
Description
A method to pad an array of arbitrary length with objects up to a specified array size does not currently exist.
Array#fill
does not do this and I therefore propose the following method:
class Array
def pad(pad_to_length, object = nil)
fill(object, size, pad_to_length - size)
end
end
I have provided an answer to a Stack Overflow question asking how this can be done in Ruby. I've also explained in a comment on the answer which suggests using Array#fill
why this does not meet the exact need.
Updated by nobu (Nobuyoshi Nakada) 10 days ago
It may be possible with Array#fill
and start-exclusive range?
ary.fill(object, -1^..padding_length)
Updated by MatzFan (Brian Cohen) 9 days ago
When I try and run that code, e.g.
[1, 2, 3].fill(nil, -1^..10)
'Integer#^': Range can't be coerced into Integer (TypeError)
In any case pad(10)
is much prettier IMHO.
Updated by nobu (Nobuyoshi Nakada) 7 days ago
Current Ruby doesn't have start-exclusive range.
^..
is so-called neko-operator in Perl 6, and just this request reminded me of it, sorry.
Updated by MatzFan (Brian Cohen) 7 days ago
No worries, I thought it was some new syntax I was not aware of!
Updated by matheusrich (Matheus Richard) 4 days ago
What should happen if the size is smaller than what currently set?
Updated by MatzFan (Brian Cohen) 4 days ago
What should happen if the size is smaller than what currently set?
If the pad_to_length
argument is less than or equal to the array's current size the array is returned unchanged. If it is larger, elements of the specified kind are pushed to the array until it reaches pad_to_length
size and the modified array returned.