User Input + Random Word and Number printing

懵懂的女人 提交于 2019-12-13 23:24:49

问题


So I have code:

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

It is supposed to display your name(that you entered), a random occupation, and a random rating but I don't know what is wrong with it. This is the satisfactory output:

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:


input and occupation are defined outside the scope of the occupationsfunction. Either declare it as a global variable with $input and $occupation, declare it inside the function or pass the variables as arguments to the function (as Lee suggested):

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

Besides, there was a typo: in occupation = occupationslist[rand1] instead of oc*c*upationslist[rand1] you wrote ocupationslist[rand1] (without the 'c').



来源:https://stackoverflow.com/questions/11145075/user-input-random-word-and-number-printing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!