我正在研究Chris Pine的Ruby教程。我必须编写一个欺骗方法,允许我设置我想要显示的骰子的哪一侧:https://pine.fm/LearnToProgram/?Chapter=09
我有两个实例变量:@numberShowing和@numberCheat。 @numberCheat收到用户的输入,我想设置@numberShowing来获取@numberCheat的值。但是,@ numberShowing总是输出一些随机数。有什么提示吗?
到目前为止,这是我的代码:
class Die
def initialize
roll
end
def roll
@numberShowing = 1 + rand(6)
end
def showing
@numberShowing
end
def cheat
puts "cheat by selecting your die number between 1 and 6"
@numberCheat = gets.chomp
end
@numberShowing = @numberCheat
end
puts Die.new.cheat
puts Die.new.showing
谢谢!
答案 0 :(得分:2)
将@numberShowing = @numberCheat
移至cheat
方法。但是你的测试不会证明它有效。尝试类似:
die = Die.new
puts "Currently showing #{die.showing}"
puts "Cheating to change showing number to #{die.cheat}"