You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby如何实现按输入语句结尾标点返回指定响应的聊天机器人功能

Ruby 聊天机器人规则匹配实现方案

实现逻辑

核心通过Ruby字符串内置的end_with?方法判断输入内容的结尾字符,按规则返回对应结果即可,实现步骤如下:

  • 第一步:获取用户输入后先清洗首尾空白字符,避免末尾空格、换行符干扰判断
  • 第二步:按优先级判断输入结尾字符,匹配对应规则返回结果

注意:如果需要同时兼容全角、半角标点,可在end_with?方法中传入多个目标字符参数

可运行示例代码

# 定义回复生成方法
def chatbot_response(user_input)
  # 清洗输入首尾空白
  cleaned_input = user_input.strip
  # 按规则匹配
  if cleaned_input.end_with?('.', '。')
    "Yes."
  elsif cleaned_input.end_with?('!', '!')
    "Stop yelling."
  elsif cleaned_input.end_with?('?', '?')
    "Sure."
  else
    # 可自定义未匹配规则的默认返回,可根据需求调整
    "I don't understand what you said."
  end
end

# 测试用例
puts chatbot_response("今天天气很好。") # 输出 Yes.
puts chatbot_response("我太开心了!") # 输出 Stop yelling.
puts chatbot_response("明天会下雨吗?") # 输出 Sure.

连续交互优化方案

如果需要实现实时连续对话,可以新增循环逻辑持续接收用户输入:

loop do
  print "你: "
  input = gets.chomp
  # 输入exit即可退出交互
  break if input.downcase == 'exit'
  puts "机器人: #{chatbot_response(input)}"
end

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:09:00