ruby 创建一个固定大小的数组,并用另一个数组填充默认内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16830956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an array with a fixed size, and fill default content with another array?
提问by rorra
I want to create a fixed size array with a default number of elements already filled from another array, so lets say that I have this method:
我想创建一个固定大小的数组,其中已经从另一个数组填充了默认数量的元素,所以可以说我有这个方法:
def fixed_array(size, other)
array = Array.new(size)
other.each_with_index { |x, i| array[i] = x }
array
end
So then I can use the method like:
那么我可以使用如下方法:
fixed_array(5, [1, 2, 3])
And I will get
我会得到
[1, 2, 3, nil, nil]
Is there an easier way to do that in ruby? Like expanding the current size of the array I already have with nil objects?
在 ruby 中是否有更简单的方法来做到这一点?就像使用 nil 对象扩展我已经拥有的数组的当前大小一样?
回答by toro2k
def fixed_array(size, other)
Array.new(size) { |i| other[i] }
end
fixed_array(5, [1, 2, 3])
# => [1, 2, 3, nil, nil]
回答by xaxxon
5.times.collect{|i| other[i]}
=> [1, 2, 3, nil, nil]
回答by Stefan
Is there an easier way to do that in ruby? Like expanding the current size of the array I already have with nil objects?
在 ruby 中是否有更简单的方法来做到这一点?就像使用 nil 对象扩展我已经拥有的数组的当前大小一样?
Yes, you can expand your current array by setting the last element via Array#[]=:
是的,您可以通过以下方式设置最后一个元素来扩展当前数组Array#[]=:
a = [1, 2, 3]
a[4] = nil # index is zero based
a
# => [1, 2, 3, nil, nil]
A method could look like this:
一种方法可能如下所示:
def grow(ary, size)
ary[size-1] = nil if ary.size < size
ary
end
Note that this will modify the passed array.
请注意,这将修改传递的数组。
回答by sawa
a = [1, 2, 3]
b = a.dup
Array.new(5){b.shift} # => [1, 2, 3, nil, nil]
Or
或者
a = [1, 2, 3]
b = Array.new(5)
b[0...a.length] = a
b # => [1, 2, 3, nil, nil]
Or
或者
Array.new(5).zip([1, 2, 3]).map(&:last) # => [1, 2, 3, nil, nil]
Or
或者
Array.new(5).zip([1, 2, 3]).transpose.last # => [1, 2, 3, nil, nil]
回答by Zack Xu
You can also do the following:
(assuming other = [1,2,3])
您还可以执行以下操作:(假设other = [1,2,3])
(other+[nil]*5).first(5)
=> [1, 2, 3, nil, nil]
if other is [], you get
如果其他是[],你会得到
(other+[nil]*5).first(5)
=> [nil, nil, nil, nil]
回答by Zack Xu
Similar to the answer by @xaxxon, but even shorter:
类似于@xaxxon 的回答,但更短:
5.times.map {|x| other[x]}
or
或者
(0..4).map {|x| other[x]}
回答by daslicious
this answer uses the fillmethod
这个答案使用了fill方法
def fixed_array(size, other, default_element=nil)
_other = other
_other.fill(default_element, other.size..size-1)
end

