用户输入+随机单词和数字打印 [英] User Input + Random Word and Number printing

查看:113
本文介绍了用户输入+随机单词和数字打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有代码:

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.

推荐答案

inputoccupationoccupations函数范围之外定义.使用$input$occupation将其声明为全局变量,将其声明为函数内部,或者将变量作为参数传递给函数(如Lee所建议的那样):

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

此外,还有一个错字:在occupation = occupationslist[rand1]中而不是oc * c * upationslist [rand1]中,您编写了ocupationslist [rand1](不带'c').

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

这篇关于用户输入+随机单词和数字打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆