Alex Rivera | Logout

Pad an array to be a certain size

Asked 2011-04-10T00:30:15.980
19

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)
end

What would you suggest?

Edit
Report

1 Answer

27

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. ljust, rjust are builtin methods for String, and I extended that convention to Array, but that corresponds to padright and padleft, respectively, in the terminology of the question.

Destructive methods

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 Array class:

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

Non-destructive methods

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

or

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
answered 2011-04-10T00:55:32.187

Your Answer