首页 > 解决方案 > 红宝石克隆一个对象

问题描述

我需要克隆一个现有对象并更改该克隆对象。问题是我的更改改变了原始对象。这是代码:

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}>

有没有办法来解决这个问题?

标签: rubyclassclonedup

解决方案


你想要.clone或者也许.dup

test2 = test.clone

但取决于你的目的,但在这种情况下,你可能想.clone 看看Ruby 的 dup 和 clone 方法有什么区别?

主要区别在于.clone还复制了对象的单例方法和冻结状态。

在旁注中,您还可以更改

options[:path] = '/' if options[:path].nil? # you don't need "== true" 

推荐阅读