Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • 123
    Remember that include? is case sensetive. So if my_string in the example above would be something like "abcDefg" (with an uppercase D), include?("cde") would return false. You may want to do a downcase() before calling include?().
    – phortx
    Commented Mar 25, 2014 at 7:58
  • 5
    Include on it's own is not ideal as it can throw a NoMethodError if nil test = nil test.include?("test") NoMethodError: undefined method `include?' for nil:NilClass should always convert the value being included to the expected value:- test.to_s.include?("test")
    – Gary
    Commented May 8, 2018 at 21:24
  • 6
    @Gary's advice holds if your goal is to minimize exceptions raised in this part of the code. That is not always the best goal. Generally if you expect a string at this point in the code and a value is nil instead, that implies something unexpected has occurred and an exception being raised is appropriate. If the existence of a nil here is unexpected, using to_s will hide the problem and increase the distance between the source and the detection of the problem, making it harder to debug. Commented May 11, 2020 at 22:11
  • 1
    Alternatively, avoid sending methods to nil with a safe navigation operator test&.include?("test") Commented Mar 30, 2022 at 16:03