---
title: "TypeError: can't convert Regexp into String"
description: "How to handle Ruby’s TypeError when using Regexp with String#include? Practical notes and code examples on TypeError: can’t."
url: "https://h3manth.com/scribe/typeerror-cant-convert-regexp-into-string/"
canonical_url: "https://h3manth.com/scribe/typeerror-cant-convert-regexp-into-string/"
markdown_url: "https://h3manth.com/scribe/blog/typeerror-cant-convert-regexp-into-string.md"
publishDate: "2012-04-30T00:00:00.000Z"
author: "Hemanth HM"
category: "ruby"
tags: ["ruby"]
word_count: 221
reading_time_minutes: 2
x_markdown_tokens: 487
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# TypeError: can't convert Regexp into String

> How to handle Ruby’s TypeError when using Regexp with String#include? Practical notes and code examples on TypeError: can’t.

**TypeError: can't convert Regexp into String in Ruby** - So what?

```ruby
#!/usr/bin/env ruby

"hemanth".include?(/hem/)

=begin
Executing the above code will result in:
TypeError: can't convert Regexp into String
=end
```

It so happens that `String#include?` takes only a string argument, not a regular expression, as the below code makes it clear:

```c
static VALUE
rb_str_include(VALUE str, VALUE arg)
{
    long i;
    StringValue(arg);
    i = rb_str_index(str, arg, 0);
    if (i == -1) return Qfalse;
    return Qtrue;
}
```

What next?

1. Override String's method! [Not advised]
2. Search for alternatives

Hunting for alternatives, I came across a simple construct in Ruby:

```ruby
[1] pry(main)> "hemanth is testing" === "hemanth"
=> false

[2] pry(main)> "hemanth is testing" =~ /hemanth/
=> 0

[3] pry(main)> "hemanth is testing"["hemanth"]
=> "hemanth"

[4] pry(main)> "hemanth is testing"[/hemanth/]
=> "hemanth"

# Holy goodness!
```

Kool isn't it? `String["sub-string"]` or `String[/R.E/]` works! This solves the issue with an easy and simple trick that also allows one to grep through any given string easily.

**Update May-2-2012:**

One of the comments @ reddit read:

```ruby
'the string4321: the string1234'[/:\D+(\d+)/, 1]
#=> '1234'
```

**Update May-3-2012:**

More civilized way of handling this issue:

```ruby
#!/usr/bin/env ruby 

def contains_text(text, target)
  if target.kind_of? Regexp
    text.match(target)
  elsif target.kind_of? String
    text.index(target)
  else
    raise TypeError, "Argument #{target} should be a string or regexp."
  end 
end
```
