我是 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/