So I am doing a small, simple project for my class and for some reason I can’t access a value using a variable.
This is my class: (I am having problems with the getAnswer method, in particular the answerArray array)
#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
This is my class to the class:
randomNum = cgi['randomNum'] answer = cgi['answer'] puts newQuestion.getAnswer(randomNum,answer)
Now the thing is that randomNum holds a value from a previous form. If I print out randomNum right under where I pull the value from the form I get it.
if I print out randomNum inside of the method getAnswer I get it.
If I print out answerArray[0] I get a value.
If I print out answerArray[randomNum] I get nothing.
It is pretty much an exact copy of the getQuestion method from above and that one works. Any input?
The random number is probably coming in as a string from your CGI. Cast it to an integer using randomNum.to_i and you’ll be set.