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

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

问题描述

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

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

puts arr.inspect
puts arr2.inspect

生产:

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

反正是有,因为我明白这是一个黑客做一个字符串数组,比使用其他元帅的深层副本。

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 | E | e.dup结束(除非你真正需要克隆的行为,建议使用 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

您可能还需要定义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天全站免登陆