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

Ruby实现不区分大小写的特定单词查找方法求助

Ruby检查字符串是否包含不区分大小写的"hello"

刚接触Ruby的话,有两种简单直接的方法可以实现这个需求:

方法一:利用大小写转换 + include?

把输入字符串统一转成小写(或大写),再检查是否包含小写的"hello",就能忽略大小写差异:

def includes_hello?(str)
  str.downcase.include?("hello")
end

测试示例:

includes_hello?("HelLO")          # 返回 true
includes_hello?("hello world")    # 返回 true
includes_hello?("Hi there")       # 返回 false

方法二:使用不区分大小写的正则表达式

Ruby的正则表达式支持i选项,表示忽略大小写,配合match?方法可直接判断:

def includes_hello?(str)
  str.match?(/hello/i)
end

这个方法和第一种效果一致,正则方式在需要更复杂匹配规则时会更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:20:23