问题
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