ruby - 红宝石克隆一个对象
问题描述
我需要克隆一个现有对象并更改该克隆对象。问题是我的更改改变了原始对象。这是代码:
require "httparty"
class Http
attr_accessor :options
attr_accessor :rescue_response
include HTTParty
def initialize(options)
options[:path] = '/' if options[:path].nil? == true
options[:verify] = false
self.options = options
self.rescue_response = {
:code => 500
}
end
def get
self.class.get(self.options[:path], self.options)
end
def post
self.class.post(self.options[:path], self.options)
end
def put
self.class.put(self.options[:path], self.options)
end
def delete
self.class.put(self.options[:path], self.options)
end
end
设想:
test = Http.new({})
test2 = test
test2.options[:path] = "www"
p test2
p test
输出:
#<Http:0x00007fbc958c5bc8 @options={:path=>"www", :verify=>false}, @rescue_response={:code=>500}>
#<Http:0x00007fbc958c5bc8 @options={:path=>"www", :verify=>false}, @rescue_response={:code=>500}>
有没有办法来解决这个问题?
解决方案
你想要.clone
或者也许.dup
test2 = test.clone
但取决于你的目的,但在这种情况下,你可能想.clone
看看Ruby 的 dup 和 clone 方法有什么区别?
主要区别在于.clone
还复制了对象的单例方法和冻结状态。
在旁注中,您还可以更改
options[:path] = '/' if options[:path].nil? # you don't need "== true"
推荐阅读
- python - 具有边缘属性的networkx中的同构
- angular - Angular 库的 npm 发布
- javascript - 如何从选择选项和输入中获取信息,另一个输入?
- jenkins-pipeline - 如何在詹金斯管道中只限制一个参数?
- r - 如果缺少需要 TRUE/FALSE 的值 - 星期几作为数字
- javascript - 显示 JavaScript 警报后重定向到 php URL
- javascript - 为什么你只删除一个项目?是否可以删除所选项目?
- spring-boot - 无论如何我们可以使用 Spring Cloud Functions + AWS Lambda 适配器来处理 http 文件上传吗?
- azure - 如何在 Microsoft azure 云中部署 index.html 文件?
- javascript - JQuery Timepicker 响应问题