arrays - 合并 Ruby 中特定索引处的数组

标签 arrays ruby

我需要一个返回从指定索引开始的合并数组的方法。我看过here , herehere无需破解它。

我可以看到这是连接的,但我想更新数组而不是简单地组合它们:

@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#[]=并传入 startlength 参数:

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/

相关文章:

java - 从对象数组中删除对象

mysql奇怪的 "duplicate entry"错误

html - Rails 4 - 由于关联,渲染 View 很慢

ruby - 无法激活 rspec-2.12.0,因为 rspec-core-2.13.1 与 rspec-core 冲突 (~> 2.12.0)

java - 将数组中的每个数字乘以 n - java

javascript - 在javascript中递归复制二维数组的算法

php - 通过数组获取mysql记录的数据?

java - 抽象类数组

ruby-on-rails - 尝试向 Controller .find 方法添加条件

ruby-on-rails - Ruby 1.9 垃圾收集器,GC.disable/enable