因此,我正在为我的类做一个小而简单的项目,出于某种原因,我无法使用变量访问值。Ruby数组 - 无法访问值
这是我的课:(我有同的getAnswer方法的问题,特别是answerArray阵列)
#Create random fact array
class RandomFact
def initialize()
@randomNum = rand(5)
end
def getQuestion
randomNum = @randomNum
questionArray = Array.new
questionArray[0] = "Do you liek mudkipz?"
questionArray[1] = "Question2"
questionArray[2] = "Three"
questionArray[3] = "Reddit"
questionArray[4] = "4chan"
puts questionArray[randomNum]
return randomNum
end
def getAnswer(randomNum,answer)
answerArray = Array.new
answerArray[0] = "one"
answerArray[1] = "two"
answerArray[2] = "three"
answerArray[3] = "four"
answerArray[4] = "five"
return answerArray[randomNum]
end
end
这是我的同班同学类:
randomNum = cgi['randomNum']
answer = cgi['answer']
puts newQuestion.getAnswer(randomNum,answer)
现在的事randomNum是否保存了前一个表单的值。如果我打印出randomNum,我从表单中获取值。
如果我打印出getAnswer方法内部的randomNum,我就可以得到它。
如果我打印出answerArray [0],我得到一个值。
如果我打印出answerArray [randomNum],我什么也没得到。
它几乎是上面getQuestion方法的一个精确副本,可以工作。任何输入?
做一个'p randomNum`和'p answer`,所以我们可以看到randomNum和答案的详细信息。 FYI`p obj`相当于`puts obj.inspect` - 它比`puts obj.to_s`提供更多的信息,通常对调试更有用。 – rampion 2009-04-11 03:16:52