gpt4 book ai didi

Ruby 类继承以及如何避免调用 super 两次

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:26 26 4
gpt4 key购买 nike

我正在构建一个国际象棋游戏。我正在尝试用组合封闭方 block 生成每个棋子,虽然我可以手动将其输入到每个类中,但我想通过继承来完成。我无法避免为每个子类调用两次 super。如果有任何帮助,我将不胜感激。

代码:

class Piece
attr_accessor :color, :piece

def initialize(color)
@color = color
@piece = "#{@piece}\u20DE"
end
end

class King < Piece
def initialize(color)
super
@piece = "♔" if @color == "white"
@piece = "♚" if @color == "black"
super
end
end

最佳答案

就个人而言,我会将此逻辑完全移出构造函数:

class Piece
attr_reader :color

def initialize(color)
@color = color
end

def piece
@piece ||= "#{base_piece}\u20DE"
end
alias :to_s :piece

private
def base_piece
self.class.const_get(color.upcase)
end
end

class King < Piece
WHITE = "♔"
BLACK = "♚"
end

puts King.new(:black), King.new(:white)
# => ♚⃞
# ♔⃞

关于Ruby 类继承以及如何避免调用 super 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35592371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com