ruby - 用映射替换数组元素

标签 ruby

我有两个数组:

@a = [ 
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
@b = [a, b, c]

我需要将 a 中的第 n 列替换为 b,如下所示:

swap_column(0)
#=> [a, 2, 3]
    [b, 5, 6]
    [c, 8, 9]

(如果有人想知道的话,这是为了使用 Cramer's rule 来求解方程组。)

我想出的代码:

  def swap_column(n)
    @a.map.with_index { |row, j| row[n] = @b[j] }
  end

如何摆脱此处的赋值,以便 map 返回修改后的矩阵,同时保持 @a 不变?

最佳答案

你想要的是dup。另外,您的 map.with_index block 的返回值是错误的。

def swap_column(i)
  @a.map.with_index{|row, j| row = row.dup; row[i] = @b[j]; row}
end

def swap_column(i)
  @a.map.with_index{|row, j| row.dup.tap{|row| row[i] = @b[j]}}
end

关于ruby - 用映射替换数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19169328/

相关文章:

ruby-on-rails - ruby on rails 中的复合主键

Ruby RSS/Atom 处理器,它知道我已经在提要中处理了哪些项目

带有 rspec "can' t 修改卡住对象的 Ruby 1.9.1"

c - 将 C 结构包装到 Ruby

ruby - 如何在 Ruby 中打开进程的 STDIN?

ruby-on-rails - Rspec:如何测试 ActiveRecord::Base.connection.execute

ruby-on-rails - ruby/rails : what is the right way to refer to some_user. user_profile.name 如果用户可能还没有 user_profile?

ruby - 为什么 ngrok 向我发送 403 Forbidden

ruby - 在循环中创建类对象

ruby - 如何在构建 ruby​​ gem 之前运行单元测试?