dreeves dreeves - 4 years ago 228
Ruby Question

Pad an array to be a certain size

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)

What would you suggest?

Answer Source

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))
def padright!(a, n, x)
  a.fill(x, a.length...n)

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

Non-destructive methods

def padleft(a, n, x)
  Array.new([0, n-a.length].max, x)+a
def padright(a, n, x)
  a.dup.fill(x, a.length...n)


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download