用户输入+随机字和数字打印

时间:2012-06-21 19:07:49

标签: ruby methods

所以我有代码:

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.

1 个答案:

答案 0 :(得分:0)

inputoccupation的定义超出了occupations函数的范围。要么将它声明为带有$input$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

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