匹配并包括?方法

Match & includes? method

我的代码是关于一个有 3 个可能答案的机器人(这取决于您在消息中输入的内容)

因此,在这个可能的答案中,取决于输入是否是一个问题,为了证明这一点,我认为它必须识别“?”字符串上的符号。

我可以使用“匹配”方法或包含吗?

这段代码将被包含在一个循环中,可能以 3 种可能的方式回答。

示例:

puts "whats your meal today?"
answer = gets.chomp 
answer.includes? "?"

or 
answer.match('?')

看看String#end_with?我认为这是你应该使用的。

改用String#match?

String#chomp will only remove OS-specific newlines from a String, but neither String#chomp nor String#end_with? will handle certain edge cases like multi-line matches or strings where you have whitespace characters at the end. Instead, use a regular expression with String#match?。例如:

print "Enter a meal: "
answer = gets.chomp
answer.match? /\?\s*\z/m

Regexp 文字 /\?\s*\z/m 将 return true 值,如果(可能 multi-line)字符串在您的 answer 包含:

  1. 一个文字问号(这就是它被转义的原因)...
  2. 后跟零个或多个空白字符...
  3. 锚定到 end-of-string 有或没有换行符,例如\n\r\n,尽管这些通常已被 #chomp 删除。

这将比您当前的解决方案更可靠,并且将处理更多种类的输入,同时更准确地查找以问号结尾的字符串,而不考虑尾随空格或行结尾。