How do I properly override instance methods in Ruby?
I've been learning Ruby for a class and have been writing a sample game. Here is a bit of one of my classes:
class Player
def askIfTake
puts("Would you like to take a card? > ")
input = gets.chomp
input.downcase!
if input == "y" or input == "yes"
return 1
elsif input == "n" or input == "no"
return 0
else
puts("Invalid input. Please type y or n.")
return askIfTake
end
end
end
I then have another class:
class PlayerAI < Player
def initialize
super
end
def askIfTake
puts("this is an AI")
return rand(2)
end
end
The problem is, when I create an instance of Pl开发者_如何学运维ayerAI, and attempt to call askIfTake from that instance, it calls the method declared in the Player class. Why is this happening?
This is not possible. I tested it (knowing it would be fine) and it worked for me:
>> PlayerAI.new
=> #<PlayerAI:0x00000103889308>
>> PlayerAI.new.askIfTake
this is an AI
You are doing this in the correct way. Check if you have any spelling mistakes. Incidentally, in Ruby the method usually uses underscores: PlayerAI.new.ask_if_take
. Or better, with a question mark: PlayerAI.new.will_take?
.
精彩评论