Ruby字符串方法.include?能否搭配感叹号运算符使用?如何判断字符串不包含内容
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:
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 endUse
unlessinstead ofif !
Ruby'sunlesskeyword 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

