There's probably a more efficient and more Ruby-ish way to do this:
# Pad array to size n by adding x's. Don't do anything if n <= a.length.
def padleft(a, n, x)
return a if n <= a.length
return padleft([x] + a, n, x)
Edited due to my misunderstanding of the question. Pervious version of my answer padded from the right side, but the question was asking to do it from the left side. I corrected it accordingly. This is due to naming convention.
rjust are builtin methods for
String, and I extended that convention to
Array, but that corresponds to
padleft, respectively, in the terminology of the question.
def padleft!(a, n, x) a.insert(0, *Array.new([0, n-a.length].max, x)) end def padright!(a, n, x) a.fill(x, a.length...n) end
It would be more natural to have it defined on
class Array def rjust!(n, x); insert(0, *Array.new([0, n-length].max, x)) end def ljust!(n, x); fill(x, length...n) end end
def padleft(a, n, x) Array.new([0, n-a.length].max, x)+a end def padright(a, n, x) a.dup.fill(x, a.length...n) end
class Array def rjust(n, x); Array.new([0, n-length].max, x)+self end def ljust(n, x); dup.fill(x, length...n) end end