2009-04-11 52 views
1

因此,我正在为我的类做一个小而简单的项目,出于某种原因,我无法使用变量访问值。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方法的一个精确副本,可以工作。任何输入?

+0

做一个'p randomNum`和'p answer`,所以我们可以看到randomNum和答案的详细信息。 FYI`p obj`相当于`puts obj.inspect` - 它比`puts obj.to_s`提供更多的信息,通常对调试更有用。 – rampion 2009-04-11 03:16:52

回答

1

随机数可能是从您的CGI以字符串形式出现。使用randomNum.to_i将其转换为整数,您将被设置。

+0

不,我曾尝试使用int()更改它。我只是试图to_i,但也没有奏效。 – Levi 2009-04-11 00:31:13

0

它必须是你的输入。当我在irb上尝试它时,它对我有用。

>> new_q = RandomFact.new 
=> #<RandomFact:0x41028e74 @randomNum=2> 
>> new_q.getQuestion 
Three 
=> 2 
>> new_q.getAnswer(2, "") 
=> "three" 
+0

我知道我的意见,我只是不知道它有什么问题。我试图转换输入以确保它是一个整数,但它仍然不起作用。输入是那里,但我可以打印出来,因为某些原因,我不能将它与数组结合使用。 – Levi 2009-04-11 02:07:26

0

我不知道你真正想在这里做的,但如果你真的只想要做你的例子显示,那么你就不需要创建类和功能。一系列的问题和答案会很好。

QA = [ 
    ["What is the capital of Estonia?","Tallinn"], 
    ["How many times to 6 go into 18?","3"], 
    ["What have I got in my pocket?","The Ring"] 
] 

qnum = cgi["qnum"].to_i 
question = QA[qnum].first 
answer = QA[qnum].last 
+0

这是一个我正在使用Ruby的课程,所以我们需要花很长时间才能了解这门语言。但是,这将是一个理想的方式来做到这一点。 – Levi 2009-04-11 02:05:22

0

您是否正在初始化newQuestion?在你给它的例子中将是零。

几个不相关的问题小技巧:你不需要return语句。 Ruby总是返回最后一个值。只要把它自己的价值。在Ruby中,标准的做法是将你的变量写成new_question而不是newQuestion。

+0

是的,我是在我的打印内容行后立即启动它,它只是不在上面的示例中。我发现我的老师写这样的变量,有什么理由吗? – Levi 2009-04-11 02:48:20

+0

什么打印内容?你的意思是在投注之后?如果是这样,那当然是行不通的。 以这种方式编写变量将会起作用,它仅仅违背Ruby约定。 如果你有你的代码缺少的部分,你会更容易得到更好的答案。 – user37011 2009-04-11 04:20:42

0

你的代码中有很多东西看起来很不规则。

无论你如何分片,在两个单独的数组中描述问题和答案都是麻烦。最好是用一个简单的,一致的数组数组来定义它们,然后使用内置的Array#rand方法选择其中的一个元素,随机选择其中的一个。

例如


    class RandomFact 
    QUESTIONS = [ 
     [ 'How many nuts can a squirrel eat?', '2' ], 
     [ 'What is my favorite color?', 'blue' ] 
    ] 

    def self.rand 
     QUESTIONS.rand 
    end 
    end 

    (question, answer) = RandomFact.rand 

    puts "Question: #{question}" 
    puts "Answer: #{answer}"