-8

所以我有代码:

puts 'What is your name?(Enter in field below)'
input = gets.chomp
puts 'end'
occupationslist = ['Engineer', 'Clerk', 'Doctor', 'Demolition Expert', 'Athlete', 'None',]
oclistlength = occupationslist.length
rand1 = rand(oclistlength)
occupation = ocupationslist[rand1]
def occupations
  puts input
  puts 'Occupation: ' + occupation
  puts 'Rating: ' + rand(1-12).to_s  
end
occupations

它应该显示您的姓名(您输入的)、随机职业和随机评级,但我不知道它有什么问题。这是令人满意的输出:

prints "What is your name?".
(gets user input)
prints out the input.
prints out a random 'occupation'(from the list in the array above).
prints out the 'Rating: ' - a random number from 0 to 12.
4

1 回答 1

0

input并且occupation在函数范围之外定义occupations$input要么用and将其声明为全局变量,要么$occupation在函数内部声明它,要么将变量作为参数传递给函数(如 Lee 建议的那样):

puts 'What is your name?(Enter in field below)'
$input = gets.chomp
puts 'end'
occupationslist = ['Engineer', 'Clerk', 'Doctor', 'Demolition Expert', 'Athlete', 'None',]
oclistlength = occupationslist.length
rand1 = rand(oclistlength)
$occupation = occupationslist[rand1]
def occupations
  puts $input
  puts 'Occupation: ' + $occupation
  puts 'Rating: ' + rand(1-12).to_s  
end
occupations

此外,还有一个错字:你写的是 ocupationslist[rand1]occupation = occupationslist[rand1]而不是 oc* c *upationslist[rand1] (没有'c')。

于 2012-06-21T19:18:18.003 回答