Hemanth's Scribes

ruby

TypeError: can't convert Regexp into String

Author Photo

Hemanth HM

Thumbnail

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

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

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:

[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:

'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
#ruby
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.