0

我被一个无法正常运行的程序卡住了。这是我的代码:

puts '<Input greeting below>'
answer = gets.chomp
if answer == 'Hello' || 'Hi'
  answer == true
else 
  answer == false
  puts 'Hey, how are you?'
  answer2 = gets.chomp
  if answer2 == 'I\'m good' || 'I\'m doing well'
    answer2 == true
  else 
    answer2 == false
    puts 'That\'s good. Would you like to know facts about ruby programming?'
    answer3 = gets.chomp
    if answer3 == 'Sure'
      answer3 == true
    else 
      answer3 == false
      puts 'Ok, well did you know that {hello, world} was the first program ever made?'
      answer4 = gets.chomp
      if answer4 == 'Yes'
        answer4 == true
      else 
        answer4 == false
        puts 'Wow, you\'re pretty good! Would you like to know another fact?'
        answer5 = gets.chomp
        if answer5 == 'Sure'
          answer5 == true
        else answer5 == false
          puts 'Alright, did you know the programming language "Ruby" 
          was developed by a Japanese techonolgist named "Yukihiro Matsumoto"
          because he wasn\'t satisfied with the other programming languages?'
        end 
      end
    end 
  end
end

Windows CMD 说我在第 29 行的“结束”部分有问题。我想不通。有人可以帮忙吗?

4

1 回答 1

3

在获得工作程序之前,您需要解决许多问题。

首先,if x == A || B并不意味着您认为它会做什么。这将评估if x == (A || B)它仅与第一个字符串比较的位置,而不是第二个字符串。要针对多个可能的匹配进行测试,最好的方法是使用case

case (answer)
when 'Hello', 'Hi'
  # Matches!
else
  # Not matched
end

您还可以通过添加额外的when子句来分解几个不同的条件,甚至可以使用正则表达式来捕捉大小写的变化,等等。

正如我在评论中添加的那样,这种嵌套if模式需要消失。您需要改为切换到状态系统:

state = :greeting

loop do
  case (state)
  when :greeting
    puts "<input greeting below>"
    case (gets.chomp)
    when "Hello", "Hi"
      state = :how_are_you
    else
      break
    end
  when :how_are_you
    puts "Hey, how are you?"
    case (gets.chomp)
    when "I'm good", "I'm doing well"
      state = :thats_good
    else
      break
    end
  # ... Additional `when` clauses.
  end
end
于 2013-05-19T22:18:55.723 回答