ruby - 如何在 Ruby 中创建复制构造函数

标签 ruby oop constructor copy copy-constructor

我是 Ruby 新手,正在编写一个游戏,其中有一个名为 Player 的类,并且在尝试复制对象时遇到问题。我的代码看起来像这样:

class Player

    attr_accessor :imprisoned
    attr_reader :name
    attr_reader :balance
    attr_accessor :freedom_card
    attr_accessor :current_box
    attr_reader :properties

    # Default constructor with no parameters
    def initialize (name = "")
        @name = name
        @imprisoned = false
        @balance = 7500
        @properties = Array.new
        @freedom_card = nil
        @current_box = nil
    end

    # Constructor with one parameter (it works)
    def self.nuevo (name)
        self.new(name)
    end

    # Copy constructor (doesn't seem to work)
    def self.copia (other_player)
        @name = other_player.name
        @imprisoned = other_player.imprisoned
        @balance = other_player.balance
        @properties = other_player.properties
        @freedom_card = other_player.freedom_card
        @current_box = other_player.current_box
        self
    end

    # ...
end

用这个测试时:

player = Player.nuevo ("John")
puts player.name
player_2 = Player.copia(player)
puts player_2.name

我明白了:

John
NoMethodError: undefined method `name' for ModeloQytetet::Player:Class

可能是什么错误?当使用复制对象中的其他属性或方法时,它也会失败,但在原始对象中一切正常。提前致谢,并对任何英语错误表示歉意(不是我的母语)。

最佳答案

在:

def self.copia(other_player)
  @name = other_player.name
  @imprisoned = other_player.imprisoned
  @balance = other_player.balance
  @properties = other_player.properties
  @freedom_card = other_player.freedom_card
  @current_box = other_player.current_box
  self
end

@Player的实例变量相关。你实际上什么也没做,只是设置一些变量并返回self,它是一个,而不是实例

你可以这样做

def self.copia(other_player)
  player = new(other_player.name)
  player.from(other_player)
  player
end

def from(other_player)
  @name = other_player.name
  @imprisoned = other_player.imprisoned
  @balance = other_player.balance
  @properties = other_player.properties
  @freedom_card = other_player.freedom_card
  @current_box = other_player.current_box
end

关于ruby - 如何在 Ruby 中创建复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53797213/

相关文章:

reactjs - 使用 find 与 includes 有什么区别?

c++ - 构造对象两次

ruby-on-rails - Ruby:如何有效地对两个哈希数组执行 "left join"

c# - ruby 中的 hmac-sha1 不同于 C# HMACSHA1

Python(OOP)列表附加错误

c++ - 用于顺序处理的高效通用缓冲队列

java - 从将为参数类型调用的 Java 类获取构造函数,不需要精确的参数和参数类型匹配

ruby-on-rails - 在 RSpec 中使用 let 和 subject 时未定义的方法响应

ruby - 在 Redis 中为 Ruby 重新创建 zdiffstore

PHP - 如何解决错误 "using $this when not in object context"?