---
title: "TypeError: Can't Convert Regexp Into String"
description: "in Ruby So what? #!/usr/bin/env ruby ’hemanth’.include?(/hem/) =begin Exectuing the above code will result in : =end It so."
url: "https://h3manth.com/scribe/typeerror-cant-convert-regexp-string/"
canonical_url: "https://h3manth.com/scribe/typeerror-cant-convert-regexp-string/"
markdown_url: "https://h3manth.com/scribe/blog/typeerror-cant-convert-regexp-string.md"
publishDate: "2012-05-01T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["ruby"]
word_count: 273
reading_time_minutes: 2
x_markdown_tokens: 582
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# TypeError: Can't Convert Regexp Into String

> in Ruby So what? #!/usr/bin/env ruby ’hemanth’.include?(/hem/) =begin Exectuing the above code will result in : =end It so.

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

#!/usr/bin/env ruby  
"hemanth".include?(/hem/)  
=begin  
Exectuing the above code will result in :  
TypeError: can't convert Regexp into String  
=end

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

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

#!/usr/bin/env ruby  
"hemanth".include?(/hem/)  
=begin  
Exectuing the above code will result in :  
TypeError: can't convert Regexp into String  
=end

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

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, /me came across a simple construct in ruby :

[1] pry(main)> "hemanth is testing" === "hemanth"  
=> false  
  
[2] pry(main)> "hemanth is testing" =~ /hemanth/  
<hemanth> => 0  
  
[3] pry(main)> "hemanth is testing"["hemanth"]  
"hemanth"  
  
[4] pry(main)> "hemanth is testing"[/hemanth/]  
<hemanth> => "hemanth"  
  
#holy goodness!

Kool is in't ? String["sub-string"] or String[/R.E/] works! This solves the issue with a easy and a simple trick that also one to grep through any give string easily.

**Update May-2-2012 :** On 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 :

#!/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
