将数组填充为特定大小

时间:2011-04-10 00:30:16

标签: ruby arrays

可能有更高效,更Ruby的方法来实现这一目标:

# 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

你会建议什么?

7 个答案:

答案 0 :(得分:24)

由于我对这个问题的误解而编辑。我的答案的透明版本从右侧填补,但问题是要求从左侧进行。我相应地纠正了它。这是由于命名约定。 ljustrjustString的内置方法,我将该约定扩展为Array,但分别对应padrightpadleft ,在问题的术语中。

破坏性方法

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

Array类上定义它是更自然的:

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

答案 1 :(得分:5)

FWIW:

def rpad(item, padding, num)
  Array(item).fill padding, Array(item).size, num
end
# rpad "initialize value(s)", 0, 3
# => ["initialize value(s)", 0, 0, 0]

答案 2 :(得分:4)

使用10填充长度,'x'成为你填充的内容,这就是右边的:

>> asdf = %w[0 1 2 3 ] #=> ["0", "1", "2", "3"]
>> asdf += (asdf.size < 10) ? ['x'] * (10 - asdf.size) : [] #=> ["0", "1", "2", "3", "x", "x", "x", "x", "x", "x"]

>> asdf = (asdf.size < 10) ? ['x'] * (10 - asdf.size) + asdf : asdf #=> ["x", "x", "x", "x", "x", "x", "0", "1", "2", "3"]

到padleft

如果对猴子补丁阵列有意义:

class Array
  def pad_right(s, char=nil)
    self + [char] * (s - size) if (size < s)
  end

  def pad_left(s, char=nil)
    (size < s) ? [char] * (s - size) + self : self
  end
end

%w[1 2 3].pad_right(5, 'x') # => ["1", "2", "3", "x", "x"]
%w[1 2 3].pad_left(5, 'x') # => ["x", "x", "1", "2", "3"]

答案 3 :(得分:2)

使用*运算符重复列表。

# 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 [x] * (n - a.length) + a
end

答案 4 :(得分:1)

这是另一个有趣的单行代码:

(适用非破坏性)

def padleft(a, n, x)
  a.dup.reverse.fill(x, a.length..n-1).reverse
end

(适用破坏性的)

def padleft(a, n, x)
  a.reverse.fill(x, a.length..n-1).reverse
end

答案 5 :(得分:1)

也许更多 Rubyish ;)

# Pad array to size n by adding x's. Don't do anything if n <= a.length.
def padleft(a, n, x)
  (n - a.size).times.inject(a) do |array, i|
    array << x
  end
end

答案 6 :(得分:0)

如果您正在使用Rails并希望在右侧填充:

[1,2,3,4,5,6].in_groups_of(4)
=> [[1, 2, 3, 4], [5, 6, nil, nil]]

这并不能回答问题,但这是我在访问此页面后最终需要的内容。希望它可以帮到某人。