如何创建破坏性功能

时间:2015-09-02 11:05:42

标签: ruby

我想创建一个破坏性的功能。让我们考虑以下示例:

def not_really_destructive_fun(arr)
  arr = [1,1,1]
  puts "arr changed to: " + arr.to_s
end
def destructive_fun(arr)
  p "Destructive function run."
  arr.map!{|x| x+= 1}
end

调用此类方法的输出如下:

a = [1,2,3]
not_really_destructive_fun a # => arr changed to: [1, 1, 1]
a # => [1, 2, 3]
destructive_fun a            # => "Destructive function run."
a # => [2, 3, 4]

map!仍然更改了原始值。但是,=没有。如何编写破坏性函数?

2 个答案:

答案 0 :(得分:2)

Ruby中的所有参数都使用call-by-sharing传递给方法。也就是说,您可以更改传递的变量的内容,但不能重新分配它(后者只会重新分配一个值,保留旧值。)

因此,应该修改内容,例如:

def not_really_destructive_fun(arr)
    # that won’t work
    # arr = [1,1,1]
    # that will
    arr.replace [1,1,1]
    # and that will
    arr.clear # array is now empty
    arr << 1 << 1 << 1
end

答案 1 :(得分:2)

您可以使用replace将数组替换为另一个数组:

def really_destructive_fun(arr)
  arr.replace([1,1,1])
  puts "arr changed to: #{arr}"
end

a = [1,2,3]
really_destructive_fun(a)
#=> arr changed to: [1, 1, 1]

a
#=> [1, 1, 1]