TypeError: can't convert Regexp into String
TypeError: can't convert Regexp into String in Ruby So what?
"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?
"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.
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 :
=> 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 :
'the string4321: the string1234'[/:\D+(\d+)/, 1]
=> '1234'
Update May-3-2012 More civilized way of handling this issue :
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
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs