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

时间:2014-09-05 01:24:43

标签: ruby

我不确定如何在我的脚本中添加yes或no部分。我想我应该使用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.: ")

3 个答案:

答案 0 :(得分:0)

对于初学者来说,您的代码很棒,目前您还不需要考虑重构代码。你可以加上这个。

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

答案 1 :(得分:0)

为你的输入添加一些检查,这是一个小的递归函数,请记住,它是无限的,直到用户输入正确的东西。

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.: ")

答案 2 :(得分:0)

除了其他答案,您还可以使用案例陈述检查字符串,然后提供正确的答案。

例如

 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