Hemanth's Scribes

web

TypeError: Can't Convert Regexp Into String

Author Photo

Hemanth HM

Thumbnail

TypeError: Can’t Convert Regexp Into String

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/
=> 0

[3] pry(main)> “hemanth is testing”[“hemanth”]
“hemanth”

[4] pry(main)> “hemanth is testing”[/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 :

‘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

#javascript#linux
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.