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
相关产品推荐
相关产品推荐

