[英]Ruby class inheritance returning undefined method
I am coding a Mastermind game in Ruby and looking to add further functionality to the game whereby the player can choose between being a 'codemaker' or 'codebreaker'.我正在编写 Ruby 中的 Mastermind 游戏,并希望为游戏添加更多功能,让玩家可以选择成为“codemaker”或“codebreaker”。 To do this I have created two classes called Codebreaker & Codemaker that inherit from the Players class.
为此,我创建了两个名为 Codebreaker 和 Codemaker 的类,它们继承自 Players class。
For reasons unknown when I create an instance of Codebreaker, then call the random_code method which it should have inherited from the Players Class I am getting 'undefined method shuffle' error message.由于未知原因,当我创建 Codebreaker 的实例时,然后调用它应该从 Players Class 继承的 random_code 方法,我收到“未定义的方法随机播放”错误消息。 Yet this method has not had a problem before with the more simplistic version.
然而,这种方法在更简单的版本之前没有问题。
class Players
attr_accessor :peg_colors, :select_role, :select_player
def initialize
@peg_colors = :peg_colors
@select_role = :select_role
@select_player = :select_player
end
def random_code
mix_colors = @peg_colors.shuffle
mix_colors[0...4]
end
def player
puts "Would you like to be the Codebreaker or Codemaker? Type your answser:"
@select_role= gets.chomp
@select_role = @select_role.downcase
end
def select_player(choice)
if choice == "codebreaker"
@select_player = Codebreaker
else
@select_player = Codemaker
end
end
def pegs
@peg_colors = ['Blue', 'Pink', 'Yellow', 'White', 'Purple', 'Green']
end
end
class Codemaker < Players
def random_code
get_code
end
def get_code ## thids needs re-coding
puts "\n"
puts "#{@peg_colors}"
puts "\n"
code = []
while code.length < 5
code.push(gets.chomp)
end
end
end
class Codebreaker < Players
def initialize
super
end
end
require_relative 'board.rb'
require_relative 'players.rb'
require_relative 'game.rb'
play = Players.new
pegs = play.pegs
codebreaker_or_codemaker = play.player
select_player = play.select_player(codebreaker_or_codemaker)
player = select_player.new
code = player.random_code
board = Board.new(code, pegs)
game = Game.new(board)
game.play
https://repl.it/@chrisrobbo/mastermind-game https://repl.it/@chrisrobbo/mastermind-game
The "shuffle" is method in Array class which should be available for all Array instances. “shuffle”是 Array class 中的方法,它应该适用于所有 Array 实例。 I see it is working fine on the repl.com link you have shared.
我看到它在您共享的 repl.com 链接上运行良好。 If you are still facing this issue, please share the error message or verify the object by which shuffle method is called.
如果您仍然遇到此问题,请分享错误消息或验证调用 shuffle 方法的 object。 I hope this helps.
我希望这有帮助。 Thank you.
谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.