我需要一个返回从指定索引开始的合并数组的方法。我看过here , here和 here无需破解它。
我可以看到这是连接的,但我想更新数组而不是简单地组合它们:
@a1 = [0,0,0,0,0]
a2 = [1,1]
def update_array(new_array)
@a1.push(*new_array)
end
update_array(a2)
我希望输出如下:
#[0,1,1,0,0] or [0,0,0,1,1]
取决于指定的索引。
最佳答案
您可以使用正常的元素分配,Array#[]=
并传入 start
和 length
参数:
Element Assignment — Sets the element at index, or replaces a subarray from the start index for length elements, or replaces a subarray specified by the range of indices.
(强调我的)所以,例如:
@a1 = [0,0,0,0,0]
a2 = [1,1]
@a1[1, a2.length] = a2
@a1 # => [0, 1, 1, 0, 0]
@a1 = [0,0,0,0,0]
@a1[@a1.length - a2.length, a2.length] = a2
@a1 # => [0, 0, 0, 1, 1]
关于arrays - 合并 Ruby 中特定索引处的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47487800/