Ruby:如何在不指向同一个对象的情况下复制变量? [英] Ruby: how can I copy a variable without pointing to the same object?

查看:37
本文介绍了Ruby:如何在不指向同一个对象的情况下复制变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,如何复制一个变量以使对原始变量的更改不影响副本?

In Ruby, how can I copy a variable such that changes to the original don't affect the copy?

例如:

phrase1 = "Hello Jim"
phrase2 = phrase1
phrase1.gsub!("Hello","Hi")
p phrase2 #outputs "Hi Jim" - I want it to remain "Hello Jim"

在这个例子中,两个变量指向同一个对象;我想为第二个变量创建一个新对象,但它最初包含相同的信息.

In this example, the two variables point to the same object; I want to create a new object for the second variable but have it contain the same information initially.

推荐答案

至于复制你可以这样做:

As for copying you can do:

phrase2 = phrase1.dup

# Clone: copies singleton methods as well
phrase2 = phrase1.clone

您也可以这样做以避免完全复制:

You can do this as well to avoid copying at all:

phrase2 = phrase1.gsub("Hello","Hi")

这篇关于Ruby:如何在不指向同一个对象的情况下复制变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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