4

我想使用的有问题的方法在gem这里(第 17-42 行):https ://github.com/rails/rails/blob/master/railties/lib/rails/generators/actions.rb

如您所见,name在第 19 行分配给第一个 arg,然后在第 23 行message分配给name,最后message在第 26 行用<<. 不幸的是,这意味着我作为第一个参数传入的字符串在方法之外发生了变异。

我有一个数组哈希,并按如下方式迭代它们:

groups = { foo: %w(foo, bar), bar: %w(foobar) }

groups.each do |group, gems|
  gems.each do |name|
    gem(name, "42")
  end
end

之后,由于内部的突变,我的哈希看起来像这样gem

groups => { foo: ["foo (42)", "bar (42)"], bar: ["foobar (42)"] }

如何在不破坏方法的情况下防止这些字符串(以及哈希及其数组)发生突变?

4

2 回答 2

5

你不能阻止方法改变它的参数(除了提交错误报告,因为这是它不应该做的事情)。

您可以做的是使用您的字符串的克隆调用该方法,如下所示:

gem(name.dup, "42")
于 2012-04-03T20:58:04.217 回答
1

您可以使用以下方式调用它name.dup

gem(name.dup, "42")

背景:随着gem(name)您将参数传递给方法。被调用方法内部的任何修改,也会改变原始变量。

name.dup您一起制作对象的副本。此副本在被调用方法内部进行了修改,但原始值未更改。


警告:dup并不总是有效,这取决于数据。dup不做深拷贝。看这个例子:

arr = ['a', 'b']
arr.dup.map{|x| x << '1'}
p arr #["a1", "b1"]

Explanation: The array arr is copied, but not the content inside the array. Inside the map you modify the data of the copied array. But the elements of the original and the copied array are the same. So you also change the content of the original array.

于 2012-04-03T20:58:19.303 回答