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

Ruby字符串方法.include?能否搭配感叹号运算符使用?如何判断字符串不包含内容

Ruby: Using include? with a Bang Operator & Checking for Non-Existence

Hey there! Let's clear up your questions about Ruby's include? method and how to check if a string doesn't contain a substring.

First off: Ruby does not have a bang version of include? (i.e., include!? doesn't exist). Bang operators (!) in Ruby are typically reserved for methods that modify the original object or perform "dangerous" operations. Since include? is a pure query method—it only returns a boolean (true/false) without changing the string itself—there's no need for a bang variant.

Now, let's look at your example code:

string = "this is a sentence about walking"
if string.!include?"running"
  puts string
end

This syntax is invalid in Ruby. You can't place the ! between the object and the method like that.

Correct Ways to Check for Non-Existence

There are two clean, idiomatic ways to do what you want:

  1. Negate the include? result with !
    Place the exclamation mark before the entire method call to flip the boolean result:

    string = "this is a sentence about walking"
    if !string.include?("running")
      puts string # This will run, since "running" isn't in the string
    end
    
  2. Use unless instead of if !
    Ruby's unless keyword is designed specifically for "if not" scenarios, making your code more readable:

    string = "this is a sentence about walking"
    unless string.include?("running")
      puts string # Same result as above, but more Ruby-like
    end
    

Both approaches work perfectly—pick whichever feels more natural for your code flow!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:05:03