if命令是否继续此代码的正确方法?

问题描述:

我不知道如何向我的脚本添加yes或no部分。我想我应该使用if命令,但我不确定我会怎么写,因为我看到的所有示例都使用数字。这是我目前有,if命令是否继续此代码的正确方法?

print("Hi there! I would like to welcome you to this program! Please, tell me your name.: ") 
name = gets 
puts("Hello there, " + name) 
print("I'm still testing everything out so please, bear with me. Now, how old are you?: ") 
age = gets 
puts("So you're " + age.chomp + " years old. ") 
print("I am now going to ask you a few questions. I'd like you to answer as best you can. ") 
print("Are you in school? Please answer, yes or no.: ") 
+0

感谢您的所有信息。我将尝试所有这些以了解每个人是如何工作的。 – Cristhian 2014-09-05 01:57:28

+0

我无法弄清楚如何获得返回命令的工作,但它确实给了我一个工作的轻微解决方法的想法。通过这里的答案,我能够使我的脚本更加复杂一点,我对它的结果感到满意。再次感谢! – Cristhian 2014-09-05 02:54:04

除了其他答案,您还可以使用case语句来检查您的字符串,然后提供正确的答案。

例如,

print "Enter your grade: " 
grade = gets.chomp 
case grade 
when "A" 
    puts 'Well done!' 
when "B" 
    puts 'Try harder!' 
when "C" 
    puts 'You need help!!!' 
else 
    puts "You just making it up!" 
end 

对于初学者,你的代码是伟大的,而现在你并不真正需要考虑重构你的代码。你可以添加这个。

print("Are you in school? Please answer, yes or no.: ") 
answer_1 = gets.chomp 
puts "your question #{answer_1}" if answer_1.eql?("yes") 
+0

这是单行控制语句。但是你也可以使用多行如果:elsif ... – 2014-09-05 01:38:00

添加一些检查您输入,继承人应该是一个小递归函数,记住,它的无限直到用户输入的东西是正确的。

def get_name 
    name = gets 
    if name 
    puts "Hello there, " + name 
    else 
    puts 'Please put a correct name' 
    return get_name 
    end 
end 

def get_age 
    age = gets 
    if not age =~ /\A\d+\z/ 
    puts("So you're " + age.chomp + " years old. ") 
    else 
    puts 'input is not a number' 
    return get_age 
    end 
end 

print("Hi there! I would like to welcome you to this program! Please, tell me your name.: ") 
get_name 

print("I'm still testing everything out so please, bear with me. Now, how old are you?: ") 

get_age 
print("I am now going to ask you a few questions. I'd like you to answer as best you can. ") 
print("Are you in school? Please answer, yes or no.: ")