复制 Ruby 字符串数组 [英] Duplicating a Ruby array of strings

查看:18
本文介绍了复制 Ruby 字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

arr = ["red","green","yellow"]

arr2 = arr.clone
arr2[0].replace("blue")

puts arr.inspect
puts arr2.inspect

产生:

["blue", "green", "yellow"]
["blue", "green", "yellow"]

除了使用 Marshal 之外,还有什么方法可以对字符串数组进行深层复制,因为我知道这是一种 hack.

Is there anyway to do a deep copy of an array of strings, other than using Marshal as i understand that is a hack.

我能做到:

arr2 = []
arr.each do |e|
  arr2 << e.clone
end

但它看起来不是很优雅,也不是很高效.

but it doesn't seem very elegant, or efficient.

谢谢

推荐答案

您的第二个解决方案可以缩短为 arr2 = arr.map do |e|e.dup end(除非你真的需要clone的行为,建议使用dup代替).

Your second solution can be shortened to arr2 = arr.map do |e| e.dup end (unless you actually need the behaviour of clone, it's recommended to use dup instead).

除了你的两个解决方案基本上是执行深拷贝的标准解决方案(尽管第二个版本只有一层深度(即,如果你在字符串数组的数组上使用它,你仍然可以改变字符串)).真的没有更好的方法了.

Other than that your two solutions are basically the standard solutions to perform a deep copy (though the second version is only one-level deep (i.e. if you use it on an array of arrays of strings, you can still mutate the strings)). There isn't really a nicer way.

这是一个适用于任意嵌套数组的递归 deep_dup 方法:

Here's a recursive deep_dup method that works with arbitrarily nested arrays:

class Array
  def deep_dup
    map {|x| x.deep_dup}
  end
end

class Object
  def deep_dup
    dup
  end
end

class Numeric
  # We need this because number.dup throws an exception
  # We also need the same definition for Symbol, TrueClass and FalseClass
  def deep_dup
    self
  end
end

您可能还想为其他容器(如 Hash)定义 deep_dup,否则您仍然会得到这些容器的浅拷贝.

You might also want to define deep_dup for other containers (like Hash), otherwise you'll still get a shallow copy for those.

这篇关于复制 Ruby 字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆